【发布时间】:2017-04-03 14:12:59
【问题描述】:
我试图在一个循环中使用 pthread_create 创建 30 个线程。我使用了正确的标头。
struct student_thread{
int id;
char * message;
};
void *student(void *i)
{
struct student_thread *s;
s = (struct student_thread *) i;
printf("%s%d\n",s->message,s->id);
//sleep(1);
pthread_exit(NULL);
}
void creat_student_thread()
{
pthread_t st[N];
struct student_thread stt[N];
int i,ct;
for(i=0;i<N;i++){
stt[i].id =i+1;
stt[i].message = "Created student thread ";
ct = pthread_create(&st[i],NULL,student,(void *) &stt[i].id);
//enqueue(Q1,stt[i].id);
if(ct){
printf("Error!Couldn't creat thread\n");
exit(-1);
}
}
}
int main()
{
creat_student_thread();
}
但输出显示只创建了 28 个线程。output 我在这里错过了什么?提前致谢。
【问题讨论】:
-
N定义在哪里? -
可能是输出刷新问题?请注意,您的一些线程报告创建乱序。尝试在
student线程函数中的printf之后使用fflush(stdout);,看看是否更好看。 -
另外,您将
&stt[i].id作为参数传递 - 这是一个int *,但在线程中您将其转换为:(struct student_thread *) i; -
creat_student_thread() 可以在任何创建的线程尝试通过 s 取消引用其值之前返回,因此使 stt 无效。然后 main() 退出,操作系统在终止进程时销毁所有线程。
-
查找
pthread_join()。你的main()可以返回并导致你的程序在你的线程开始之前退出。
标签: c multithreading pthreads