【发布时间】:2015-12-08 06:07:10
【问题描述】:
我是 使用 c 进行 Pthread 编程的新手 我碰巧从网上获取了以下代码
#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS 5
void *PrintHello(void *threadid)
{
long tid;
tid = (long)threadid;
printf("Hello World! It's me, thread #%ld!\n", tid);
pthread_exit(NULL);
}
int main (int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int rc;
long t;
for(t=0; t<NUM_THREADS; t++){
printf("In main: creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
if (rc)
{
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
/* Last thing that main() should do */
pthread_exit(NULL);
}
每次运行上述代码时,收到的输出都会有所不同。 有什么错误原因吗?
【问题讨论】:
-
您在此处打印线程 ID,每个线程都不同..
-
@Naresh:代码打印
t在for循环中分配的main()的值。 -
代码中唯一的错误是它很可能错过了原型
exit()。 -
谢谢我能解决问题。