首页 > 想在线程中定义变量,怎么办

想在线程中定义变量,怎么办

想在线程中定义数组,保存线程处理的结果,这里简化为保存自己的tid,但是运行有问题,buff改成全局变量共享也不行,该怎么实现线程的私有变量啊

void thread_routine()
{
    char buff[10];
    memset(buff,0,10);
    sprintf(buff,"%d",pthread_self());
    printf("%d\n", buff);
}

int main(int argc, char const *argv[])
{
    int i;
    pthread_t threadidset[3];
    for (i = 0; i < 3; i++)
    {
        pthread_create (&threadidset[i], NULL, thread_routine,
                NULL);
    }

    for (i = 0; i < 3; i++)
        pthread_join (threadidset[i], NULL);
    return 0;
}

线程处理结果可以直接返回呀

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

void *thread_routine()
{
    return (void *) 555;
}

int main(int argc, char const *argv[])
{
    int i;
    pthread_t threadidset[3];
    void *rets[3];

    for (i = 0; i < 3; i++)
    {
        pthread_create (&threadidset[i], NULL, thread_routine,
                NULL);
    }

    for (i = 0; i < 3; i++) {
        pthread_join(threadidset[i], &rets[i]);
        printf("Thread %d returns %d.\n", i, (int) rets[i]);
    }

    return 0;
}

pthread_setspecific函数设置线程私有数据。

具体用法可以google找,很多的。

http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_getspecific.html

http://stackoverflow.com/questions/14260668/how-to-use-thread-specific-data-correctly


参考一下。。

struct thread_data
{
    char data[20];
};

void thread_routine(void *arg)
{
    struct thread_data *data = (struct thread_data*)arg;
    
    memset(data->data, 0, sizeof(data->data));
    sprintf(data->data, "%d", pthread_self());
// !!    printf("%d\n", data->data);
    printf("%s\n", data->data);
}

int main(int argc, char const *argv[])
{
    int i;
    pthread_t threadidset[3];
    struct thread_data data[3];
    for (i = 0; i < 3; i++)
    {
        pthread_create (&threadidset[i], NULL, thread_routine,
                (void*)&data[i]);
    }

    for (i = 0; i < 3; i++)
        pthread_join (threadidset[i], NULL);
    return 0;
}
【热门文章】
【热门文章】