线程同步未获得预期的输出

时间:2013-03-03 12:32:35

标签: c++ multithreading pthreads

我没有得到任何输出,但我期待输出为 THREAD1 THREAD2 以下代码..

#include<iostream>
#include<pthread.h>

using namespace std;

void* fun(void *arg)
{
   char *msg;
   msg = (char*)arg;
   cout<<msg<<endl;
}

int main()
{

   pthread_t t1,t2;

   t1 = pthread_create(&t1,NULL,fun,(void*)"THREAD1");
   t2 = pthread_create(&t2,NULL,fun,(void*)"THREAD2");

   pthread_join(t1,NULL);
   pthread_join(t2,NULL);
  // sleep (2);
   return 0;
}

我将上面的代码更改为

   pthread_create(&t1,NULL,fun,(void*)"THREAD1");
   pthread_create(&t2,NULL,fun,(void*)"THREAD2");

现在我得到了 THREAD2 THREAD1 ,但我需要 THREAD1 THREAD2

现在我将代码更改为&gt;

pthread_create(&t1,NULL,fun,(void*)"THREAD1");
pthread_join(t1,NULL);    

pthread_create(&t2,NULL,fun,(void*)"THREAD2");
pthread_join(t2,NULL);

现在我的结果正确为 THREAD1 THREAD2

1 个答案:

答案 0 :(得分:3)

t1 = pthread_create(&t1,NULL,fun,(void*)"THREAD1");

那不好。 pthread_create返回整数返回码,而不是pthread_t。您使用不应存在的内容覆盖t1t2,随后的pthread_join调用可能会崩溃或产生其他不可预测的结果。

int rc1 = pthread_create(...);
if (rc1 != 0) { 
  // handle error
}

同样fun需要按照您定义的方式返回某些内容。或者将其返回类型更改为void。

相关问题