且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将参数传递给pthread_create函数

更新时间:2022-06-27 02:41:08

您必须等待使用pthread_join完成主线程中的所有线程,然后才能看到所有线程都显示一些值

You have to wait for all the threads to complete in the main using pthread_join, only then u can see all of them display some value

#include <stdio.h>
#include <pthread.h>

#define THREAD_NUM 10

void *thread_func(void *arg)
{
    int v = (int)arg;

    printf("v = %d\n", v);

    return (void*)0;
}

int main(int argc, const char *argv[])
{
    pthread_t pids[THREAD_NUM];
    int rv;
    int i;

    for (i = 0; i < THREAD_NUM; i++) {
        rv = pthread_create(&pids[i], NULL, thread_func, (void*)i);
        if (rv != 0) {
           perror("failed to create child thread");
           return 1;
        }
    }
    for (i = 0; i < THREAD_NUM; i++) {
        pthread_join(pids[i], NULL);
    }
    return 0;
}

示例运行输出:

[root@fc ~]# ./a.out
v = 0
v = 2
v = 4
v = 6
v = 7
v = 8
v = 9
v = 5
v = 3
v = 1