简体   繁体   English

C,如何使用pthread_create函数创建线程

[英]C , how to create thread using pthread_create function

I'm making ac file for a dispatch queue that gets a task and put it in to a queue which is the linked list. 我正在为一个调度队列制作一个ac文件,该队列获取一个任务并将其放入一个链接列表的队列中。 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. 但是我需要创建另一个作为'work'和'param'变量的函数作为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 ? 我的朋友告诉我,我只需要在无限循环的工作函数中放入任何代码,这样线程就不会死。任何人都可以解释每个参数进入pthread_create函数 - 特别是对于workparam I searched Google for this, but most of tutorials are so hard to understand the concept... 我搜索谷歌这个,但大多数教程都很难理解这个概念......

The four parameters to pthread_create are, in order: pthread_create的四个参数依次为:

  1. A pointer to a pthread_t structure, which pthread_create will fill out with information on the thread it creates. 指向pthread_t结构的指针, pthread_create将使用其创建的线程填充信息。

  2. A pointer to a pthread_attr_t with parameters for the thread. 指向带有线程参数的pthread_attr_t的指针。 You can safely just pass NULL most of the time. 您可以安全地在大多数时间传递NULL

  3. A function to run in the thread. 一个在线程中运行的函数。 The function must return void * and take a void * argument, which you may use however you see fit. 该函数必须返回void *并获取一个void *参数,您可以使用它,但是您认为合适。 (For instance, if you're starting multiple threads with the same function, you can use this parameter to distinguish them.) (例如,如果您使用相同的函数启动多个线程,则可以使用此参数来区分它们。)

  4. The void * that you want to start up the thread with. 要启动线程的void * Pass NULL if you don't need it. 如果您不需要,则传递NULL

clarifying duskwuff's answer: 澄清duskwuff的答案:

work parameter is a function pointer. work参数是一个函数指针。 The function should take one argument which is indicated as type void * and return value void * . 该函数应该采用一个参数,该参数表示为类型void *并返回值void *

param is expected to be a pointer to the data that work will receive. param应该是指向work将接收的数据的指针。

As an example, lets say you want to pass two int to the worker. 举个例子,假设您想将两个int传递给worker。 Then, you can create something like this: 然后,你可以创建这样的东西:

int *param = (int *)malloc(2 * sizeof(int));
param[0] = 123;
param[1] = 456;
pthread_create(&cThread, NULL, work, param);

Then your work function can convert the pointer type and grab the param data: 然后你的工作函数可以转换指针类型并获取参数数据:

void *work(void * parm) {
    int *param = (int *)parm;
    int first_val = param[0];
    ....
}

You can do more complex stuff, like creating a struct with all of the data you need to pass. 您可以执行更复杂的操作,例如创建包含您需要传递的所有数据的结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM