C中创建多线程

Creating multiple threads in C

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

看了很多教程后,我对如何使用 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_t)。

在您的代码片段中,两者都只创建一个线程。所以如果你只想创建一个线程,你不需要数组。但这就像声明您没有使用的任何变量一样。这是无害的。

事实上,如果您出于任何目的不需要线程 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 *.

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

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

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

多线程示例:

#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);    
}

对于每个人,使用一个线程列表,因为如果你调用一次它就不会免费pthread_join()

Code exemple :

int run_threads(void)
{
    int listLength = 5;
    pthread_t thread[listLength];

    //Create your threads(allocation).
    for (int i = 0; i != listLength; i++) {
        if (pthread_create(&thread[i], NULL, &routine_function, NULL) != 0) {
            printf("ERROR : pthread create failed.\n");
            return (0);
        }
    }
    //Call pthread_join() for all threads (they will get free) and all threads 
    //will terminate at this position.
    for (int i = 0; i != listLength; i++) {
        if (pthread_join(thread[i], NULL) != 0) {
            printf("ERROR : pthread join failed.\n");
            return (0);
        }
    }
    //return 1 when all threads are terminated.
    return (1);
}