c - 传递给 pthread 后结构发生变化

标签 c pthreads

我正在尝试创建一个必须创建一系列 pthread 的函数。我试图通过为每个线程分配一个唯一的 int t 来跟踪它。然而,当我尝试创建多个线程时,每当我在主函数中增加 t 的值时,它的值就会发生变化。它应该按值传递,那么为什么要改变呢?

// Struct //
typedef struct threadArg {
  int verbose;
  int listSize;
  int thread;
  int (*list)[];
} threadArg;

// In main //
for(t=0; t < numThreads; t++){
    printf("Creating thread %ld...\n", t);
    struct threadArg arg = {
      .verbose = verbose,
      .list = &arr,
      .listSize = size,
      .thread = t
    };
    printf("t: %d\n", (arg.thread));
    status = pthread_create(&threadID[t], NULL, threadSort, (void*)&arg);
    if (status){
      printf("ERROR: failed to create thread", t);
      exit(-1);
    }
  }

// Thread Sort function //
void *threadSort(void* arguments) {
  // *** Bubble Sort ***                                                                                                                                                             
  threadArg* arg = (threadArg*) arguments;
  int verbose = arg->verbose;
  int size = arg->listSize;
  int (*arr)[size] = arg->list;
  int t = arg->thread;
  if (verbose & INIT) { printf("Thread %d initalized!\n", t); }
}

感谢您的帮助, 沃利

最佳答案

It should be pass by value

不,这一行“通过引用”传递它,即传递 arg 的地址:

status = pthread_create(&threadID[t], NULL, threadSort, (void*)&arg)

代码中的 arg 实例会在循环的每次迭代中使用、销毁和重新创建。

要修复此修改,您可以编写如下代码:

void * threadSort(void * arguments);

[...]

  struct threadArg arg = {
    .verbose = verbose,
    .list = &arr,
    .listSize = size,
    .thread = 0,
  };

  struct threadArg args[t] = {0};

  for(t=0; t < numThreads; t++)
  {
    printf("Creating thread %ld...\n", t);
    args[t] = arg;
    args[t].thread = t;
    printf("t: %d\n", arg.thread);
    status = pthread_create(threadID + t, NULL, threadSort, args + t);

    [...]

这引入了一个struct arg数组,其中每个独立线程都有一个元素,由threadArg的值初始化,该数组不在其他地方使用,但有一个共同的线程wag 的初始化被传递给线程函数。

关于c - 传递给 pthread 后结构发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22489359/

相关文章:

c++ - 如何确定符号链接(symbolic link)指向的文件路径?

c - 如何向其他线程发送包含更多信息的信号?

c++ - 使用 cpp 恢复 pthread

c - 多个 pthread 加入一个 pthread 的替代方案?

c - 散列密码并使用 C 中的签名进行检查

c - 为什么 string.h 函数会出现段错误?

sockets - 在套接字编程中,accept() 可以在多进程(线程)中使用同一个监听套接字吗?

c++ - 处理线程失控问题的线程新手

C 中的回调函数与普通函数

mysql - Windows 8.1 上 MySQL 的 CodeBlocks 链接器问题