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

发布于 2022-09-02 10:39:20 字数 547 浏览 18 评论 0

想在线程中定义数组,保存线程处理的结果,这里简化为保存自己的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;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

笑红尘 2022-09-09 10:39:21

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

#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;
}
本宫微胖 2022-09-09 10:39:21

参考一下。。

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文