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

Thread Synchronization not getting expected output

本文关键字:输出 同步 线程      更新时间:2023-10-16

我没有得到任何输出,但我希望输出,因为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

现在我把代码改为>

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

现在我的结果是正确的THREAD1 THREAD2

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需要按照您定义的方式返回something。或者将其返回类型更改为void。