将参数传递给pthread_create函数 [英] pass arguments to the pthread_create function

查看:121
本文介绍了将参数传递给pthread_create函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用pthread_create创建10个子线程,将整数传递给thread_func

I use pthread_create to create 10 child threads, passes an integer to the thread_func

#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;
        }
    }
    return 0;
}

我想知道为什么每次都输出不同的结果 v = 1 v = 2 ... v = 9

I was wondering why it outputs different result everytime not just v = 1 v = 2 ... v = 9

推荐答案

您必须等待使用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

这篇关于将参数传递给pthread_create函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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