gpt4 book ai didi

c - 确保每个线程的执行

转载 作者:行者123 更新时间:2023-12-03 12:52:15 26 4
gpt4 key购买 nike

我想运行4个不同的线程,调用相同的方法,并且我想确保每次运行都来自不同的运行线程。

使用下面提供的代码,方法功能可以运行预期的次数,但始终由同一线程完成(打印值不变)。

为了确保这种情况,我应该在代码中进行哪些更改? (这将在本示例中打印出4个不同的值)

编辑:相同的代码,但包括一个结构,以查看解决方案将如何

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

struct object{
int id;
};

void * function(void * data){

printf("Im thread number %i\n", data->id);
pthread_exit(NULL);

}

int main(int argc, char ** argv){

int i;
int error;
int status;
int number_threads = 4;

pthread_t thread[number_threads];

struct object info;

for (i = 0; i < number_threads; ++i){

info.id = i;

error = pthread_create(&thread[i], NULL, function, &info);

if(error){return (-1);}
}

for(i = 0; i < number_threads; i++) {

error = pthread_join(thread[i], (void **)&status);

if(error){return (-1);}
}

}

最佳答案

您总是看到相同值(value)的原因

您正在将指针打印为整数。 data指向i中的变量maini的地址不会更改,因此将打印相同的值。

打印i的值

您要做的是将data取消引用为整数。正确的方法很简单:*(int *)data。这意味着将data转换为指向整数的指针,然后解引用以获取该值。

What should I change in the code to assure this condition? (which will result in this example in having 4 different values printed)



打印 i 的值将不会保证打印4个不同的值。
  • 完全合理的情况是,调度程序将在创建所有4个线程并且主线程正在等待join()之前不运行您的线程。在这种情况下,所有线程都将打印0
  • 线程1和2可能读取i = 2,线程3和4可能读取i = 3。或其他一些组合。

  • 如何确保打印不同的值

    为了正确执行此操作,您需要将不同的参数传递给每个线程。
    最干净的是这样的。
    int thread_number[4] = {0, 1, 2, 3};
    // ...
    error = pthread_create(&thread[i], NULL, function, &thread_number[i]);

    关于c - 确保每个线程的执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29978708/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com