在 C 中创建多个线程 [英] Creating multiple threads in C

查看:61
本文介绍了在 C 中创建多个线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am just a beginner in Programming using C.For my college project I want to create a multi-threaded server application to which multiple clients can connect and transfer there data which can be saved in a database.

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

After going through many tutorials I got confused about how to create multiple threads using 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);

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

I tried by implementing both in my application and seems to be working fine. Which approach of the above two is correct which I should follow. sorry for bad english and description.

推荐答案

两者是等价的.这里没有正确"或错误"的方法.

Both are equivalent. There's no "right" or "wrong" approach here.

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

Typically, you would see the later when creating multiple threads, so an array of thread identifiers (pthread_t) are used.

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

In your code snippets, both create just a single thread. So if you want to create only one thread, you don't need an array. But this is just like declaring any variable(s) that you didn't use. It's just harmless.

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

In fact, if you don't need the thread ID for any purpose, (for joining or changing attributes etc), you can create multiple threads using a single thread_t variable without using an array.

以下

pthread_t thr;
size_t i;

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

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

would work just fine. Note that the cast to void* is unnecessary (last argument to pthread_create()). Any data pointer can be implicitly converted to void *.

这篇关于在 C 中创建多个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆