C 线程同时运行

C 线程同时运行,c,unix,pthreads,C,Unix,Pthreads,所以我想有3个线程,它们都递增一个全局整数。我认为,当一个线程被创建时,它将与主线程中的一个分支同时执行代码。但这并不是发生的事情,因为第二个和第三个线程直到第一个线程完成后才被创建 void * say_it( void * ) { int count = 0; while(BUFFER < 24) { //LOCK if (pthread_mutex_lock(&output_lock) != 0) { perro

所以我想有3个线程,它们都递增一个全局整数。我认为,当一个线程被创建时,它将与主线程中的一个分支同时执行代码。但这并不是发生的事情,因为第二个和第三个线程直到第一个线程完成后才被创建

void * say_it( void * )
{
  int count = 0;

  while(BUFFER < 24)
    {

      //LOCK
      if (pthread_mutex_lock(&output_lock) != 0)
    {
      perror("Could not lock output: ");
      exit(-1);
    }

      //print message
      cout << "TID: " << pthread_self() << " PID: " << "WORK IN PROGRESS " << "Buffer: " << BUFFER << endl;
      BUFFER++;

      //UNLOCK
      if (pthread_mutex_unlock(&output_lock) != 0)
    {
      perror("Could not unlock output: ");
      exit(-1);
    }
      count++;
    }

  //print final message
  cout << "TID: " << pthread_self() << " worked on the buffer " << count << " times" << endl; 

}

int main(int argc, char *argv[])
{

  int num_threads = 3;
   pthread_t *thread_ids;
   void  *p_status;

   //Use unbuffered output on stdout
   setvbuf(stdout, (char *) NULL, _IONBF, 0);

   //Set up an output lock so that threads wait their turn to speak.
   if (pthread_mutex_init(&output_lock, NULL)!=0)
     {
       perror("Could not create mutex for output: ");
       return 1;
     }

   //Create 3 THREADS
   thread_ids = new pthread_t[num_threads];

   // generate threads 
   for (int i = 0; i < num_threads; i++)
     {

       int *arg = new int;
       *arg = i;
       if( pthread_create(&thread_ids[i],NULL,say_it,NULL) > 0)
       {
         perror("creating thread:");
         return 2;
       }

       if (pthread_join(thread_ids[i], &p_status) != 0)
       {
         perror("trouble joining thread: ");
         return 3;
       }
     }




   return 0;
}
void*说出它(void*)
{
整数计数=0;
而(缓冲区<24)
{
//锁
if(pthread\u mutex\u lock(&output\u lock)!=0)
{
perror(“无法锁定输出:”);
出口(-1);
}
//打印消息

cout当您调用
pthread\u join
时,main将阻塞,直到该线程完成。在对线程调用
pthread\u join
之前,您需要创建所有线程


旁注:您在注释后再次调用
pthread\u create
//连接线程并打印其返回值
。所有这些都需要删除。

在循环中,您创建一个线程,然后与它连接,因此在第一个线程完成之前不会创建下一个线程。此处没有并发


第二个循环(10)看起来完全错误,因为您只为3个线程ID分配了空间,但在这里您正在创建10个线程。

您正在创建线程并等待线程完成。请按如下所示将连接代码移出for循环

   for (int i = 0; i < num_threads; i++)
     {

       int *arg = new int;
       *arg = i;
       if( pthread_create(&thread_ids[i],NULL,say_it,NULL) > 0)
       {
         perror("creating thread:");
         return 2;
       }

     }
   for (int i = 0; i < num_threads; i++)
     {

       if (pthread_join(thread_ids[i], &p_status) != 0)
       {
         perror("trouble joining thread: ");
         return 3;
       }
     }
for(inti=0;i0)
{
perror(“创建线程:”);
返回2;
}
}
对于(inti=0;i
pthread\u join
等待线程完成。因此,在第一个线程与主线程“连接”之前,您不会创建第二个线程。这是一个复制粘贴错误:您的
“连接”
code调用
pthread\u create
,而您的创建循环一直在调用
pthread\u join
。抱歉,我本想在发布此消息之前删除最后一个线程(我猜是:/)。我刚刚编辑此消息以删除它,我们需要询问问题创建者,他可能想将其传递给线程函数。