C、如何使用pthread_create函数创建线程
我正在为调度队列制作 ac 文件,该队列获取任务并将其放入链表队列中。为了做到这一点,我需要使用创建线程
pthread_t cThread;
if(pthread_create(&cThread, NULL, work, param)){
perror("ERROR creating thread.");
}
但是我需要创建另一个函数,该函数进入“work”和“param”变量作为创建函数的参数。我的朋友告诉我,我只需要将任何代码放入无限循环的工作函数中,这样线程就不会死掉。任何人都可以解释一下进入 pthread_create 函数的每个参数 - 特别是对于 工作
和参数
?我在谷歌上搜索了这个,但大多数教程都很难理解这个概念......
I'm making a c file for a dispatch queue that gets a task and put it in to a queue which is the linked list. In order to do this, I need to create threads using
pthread_t cThread;
if(pthread_create(&cThread, NULL, work, param)){
perror("ERROR creating thread.");
}
However I need to make another function that goes into 'work' and 'param' variable as parameters of create function. My friend told me that I just need to put any code in the work function that loops infinitely so the thread does not die.. Can anyone explain each parameter goes in to the pthread_create
function- especially for work
and param
? I searched Google for this, but most of tutorials are so hard to understand the concept...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
pthread_create
的四个参数按顺序为:指向
pthread_t
结构的指针,pthread_create
将使用有关该结构的信息来填充该结构。它创建的线程。指向带有线程参数的
pthread_attr_t
的指针。大多数时候您可以安全地传递NULL
。在线程中运行的函数。该函数必须返回
void *
并采用void *
参数,您可以根据需要使用该参数。 (例如,如果您使用相同的函数启动多个线程,则可以使用此参数来区分它们。)您要启动线程的
void *
。如果不需要,请传递NULL
。The four parameters to
pthread_create
are, in order:A pointer to a
pthread_t
structure, whichpthread_create
will fill out with information on the thread it creates.A pointer to a
pthread_attr_t
with parameters for the thread. You can safely just passNULL
most of the time.A function to run in the thread. The function must return
void *
and take avoid *
argument, which you may use however you see fit. (For instance, if you're starting multiple threads with the same function, you can use this parameter to distinguish them.)The
void *
that you want to start up the thread with. PassNULL
if you don't need it.澄清 duskwuff 的答案:
work
参数是一个函数指针。该函数应采用一个参数,该参数表示为类型void *
和返回值void *
。param
应该是指向work
将接收的数据的指针。举个例子,假设您想将两个 int 传递给工作者。然后,您可以创建如下内容:
然后您的工作函数可以转换指针类型并获取参数数据:
您可以做更复杂的事情,例如使用您需要传递的所有数据创建一个结构体。
clarifying duskwuff's answer:
work
parameter is a function pointer. The function should take one argument which is indicated as typevoid *
and return valuevoid *
.param
is expected to be a pointer to the data thatwork
will receive.As an example, lets say you want to pass two int to the worker. Then, you can create something like this:
Then your work function can convert the pointer type and grab the param data:
You can do more complex stuff, like creating a struct with all of the data you need to pass.