【问题标题】:Creating multiple threads in C在 C 中创建多个线程
【发布时间】:2016-01-28 12:43:36
【问题描述】:

我只是使用 C 编程的初学者。对于我的大学项目,我想创建一个多线程服务器应用程序,多个客户端可以连接到该应用程序并在那里传输可以保存在数据库中的数据。

在阅读了许多教程后,我对如何使用 pthread_create 创建多个线程感到困惑。

在某处它是这样完成的:

pthread_t thr;

pthread_create( &thr, NULL ,  connection_handler , (void*)&conn_desc);

在某个地方就像

 pthread_t thr[10];

 pthread_create( thr[i++], NULL ,  connection_handler , (void*)&conn_desc);

我尝试在我的应用程序中实现这两者,并且似乎工作正常。我应该遵循以上两种方法中的哪种方法是正确的。 抱歉英语和描述不好。

【问题讨论】:

  • 他们都使用相同的方法pthread_create,所以在某种意义上他们在做同样的事情。除此之外,如何存储 pthread 句柄(pthread_t 类型)是一个选择问题。第二个好像最多存储十个线程,第一个只是处理一个线程。
  • 第二个thr[i++]应该是&thr[i++]
  • @Selçuk Cihan 如果我做类似 for(i=0;i
  • 是的,它将创建 10 个线程,但您将丢失前 9 个线程的引用。

标签: c multithreading pthreads


【解决方案1】:

两者是等价的。这里没有“正确”或“错误”的方法。

通常,您会在创建多个线程时看到后者,因此使用了一组线程标识符 (pthread_t)。

在您的代码 sn-ps 中,两者都只创建一个线程。因此,如果您只想创建一个线程,则不需要数组。但这就像声明您未使用的任何变量一样。它是无害的。

事实上,如果您不需要线程 ID 用于任何目的(用于连接或更改属性等),您可以使用单个 thread_t 变量创建多个线程,而无需使用数组。

以下

pthread_t thr;
size_t i;

for(i=0;i<10;i++) {
   pthread_create( &thr, NULL , connection_handler , &conn_desc);
}

会工作得很好。请注意,强制转换为void* 是不必要的(pthread_create() 的最后一个参数)。任何数据指针都可以隐式转换为void *

【讨论】:

  • @I3x 如果我需要创建 100 个线程,那么我需要使用 pthread_t thr[100] 遵循第二种方法,否则第一种方法也能解决我的问题。
  • 即使你想创建 100 个线程,你仍然不需要使用数组 (pthread_t thr[100])。如果您以后想对它们做一些事情,您只需要存储 ID。所以这取决于你的应用程序。查看更新。
  • @Ramanujam - 使用pthread_t thr[100] 会更容易,特别是如果您希望所有 100 个线程都做同样的事情。否则,您需要 100 个变量来跟踪 pthread_t 句柄。
【解决方案2】:

多线程示例:

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

using namespace std;

#define NUM_THREADS 5

struct thread_data
{
  int  thread_id;
  char *message;
};


void *PrintHello(void *threadarg)
{
   struct thread_data *my_data;   

   my_data = (struct thread_data *) threadarg;

   cout << "Thread ID : " << my_data->thread_id ;

   cout << " Message : " << my_data->message << endl;

   pthread_exit(NULL);
}

int main ()
{
   pthread_t threads[NUM_THREADS];

   struct thread_data td[NUM_THREADS];

   int rc, i;


   for( i=0; i < NUM_THREADS; i++ )    
   {

      cout <<"main() : creating thread, " << i << endl;

      td[i].thread_id = i;

      td[i].message = "This is message";

      rc = pthread_create(&threads[i], NULL,

                          PrintHello, (void *)&td[i]);

      if (rc){

         cout << "Error:unable to create thread," << rc << endl;

         exit(-1);    
      }    
   }    
   pthread_exit(NULL);    
}

【讨论】:

    【解决方案3】:

    您提供的第一个线程会创建一个线程。

    第二个(如果循环)有可能产生 10 个线程。

    基本上 pthread_t 类型是线程的处理程序,因此如果您有一个由 10 个数组组成的数组,那么您可以有 10 个线程。

    【讨论】:

      猜你喜欢
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 2019-05-01
      • 2018-07-03
      • 2020-01-19
      • 1970-01-01
      • 1970-01-01
      • 2015-05-24
      相关资源
      最近更新 更多