我在我的Windows7机器上使用MINGW进行POSIX线程编码。
考虑下面的简单代码:
#include <stdio.h>
#include <pthread.h>
#include <process.h>
#define NUM_THREADS 5
void *PrintHello(void *threadid)
{
long tid;
tid = (long)threadid;
printf("Hello Dude...!!!\t I am thread no #%ld\n",tid);
pthread_exit(NULL);
}
int main()
{
pthread_t thread[NUM_THREADS];
int rc;
long t;
for(t=0;t<NUM_THREADS;t++)
{
printf("Inside the Main Thread...\nSpawning Threads...\n");
rc=pthread_create(&thread[t],NULL,PrintHello,(void*)t);
if(rc)
{
printf("ERROR: Thread Spawning returned code %d\n",rc);
exit(-1);
}
}
return 0;
}当上面的程序在我的系统中执行时,它会显示以下输出:
Inside the Main Thread...
Spawning Threads...
Inside the Main Thread...
Spawning Threads...
Hello Dude...!!! I am thread no #0
Inside the Main Thread...
Spawning Threads...
Hello Dude...!!! I am thread no #1
Inside the Main Thread...
Spawning Threads...
Hello Dude...!!! I am thread no #2
Inside the Main Thread...
Spawning Threads...这个程序应该会产生5个线程。但它只创建了2个线程。前两行和最后两行表明即将调用pthread_create()例程。由于"rc“变量不是"1”,因此在线程创建过程中毫无疑问会出现任何错误,否则它将命中"if(rc)“部分。
那么错误在哪里呢?或者它是与我的windows机器有关的东西。
发布于 2013-06-09 15:30:28
没有错误。
你的程序在其他线程有机会输出任何东西之前就退出了,退出你的程序会杀死它的所有线程。
如果你想让所有的线程都正常的完成,你需要pthread_join所有的线程。
发布于 2013-06-09 15:30:15
实际上,真正的问题是,当你的main结束时,你的程序也会结束。在从main返回之前,您应该对它们执行pthread_join操作。其他线程没有机会在main退出之前运行,这会占用整个进程空间(以及未运行的线程)。
for(t=0;t<NUM_THREADS;t++)
{
printf("Inside the Main Thread...\nSpawning Threads...\n");
rc=pthread_create(&thread[t],NULL,PrintHello,(void*)t);
if(rc)
{
printf("ERROR: Thread Spawning returned code %d\n",rc);
exit(-1);
}
}
/* add this and you're golden! */
for(t=0; t<NUM_THREADS;t++) {
pthread_join(thread[t], NULL);
}以下是我最初的答案,也是一个很好的建议:
不要将long作为void*传递。传递它的地址。如果需要,可以在每次循环中复制一份,以便传递并在以后释放它。
long thread_data[NUM_THREADS];
for(t=0;t<NUM_THREADS;t++)
{
thread_data[t] = t;
printf("Inside the Main Thread...\nSpawning Threads...\n");
rc=pthread_create(&thread[t],NULL,PrintHello,(void*)&(thread_data[t]));
if(rc)
{
printf("ERROR: Thread Spawning returned code %d\n",rc);
exit(-1);
}
}https://stackoverflow.com/questions/17007384
复制相似问题