c - pthread_create 是否从指针复制参数值?

标签 c pthreads

假设我要创建 N 个线程,并且将不同的字符串传递到每个线程中。

伪代码:

for (i = 0; i < N; i++) {
   strncpy(arg.str, some_new_str, sizeof(arg.str));
   pthread_create(&threads[i],NULL,somefunc, (void *) &arg);
}

每个线程中arg指向的字符串会改变吗?假设对于创建的第一个线程,some_new_str 是“hello”,对于第二个线程,它是“bye”。稍后,当我在线程 1 中打印该字符串时,该字符串是否会更改为“bye”而不是“hello”?

编辑:那么我应该为每个线程创建一个新的 arg 结构?

最佳答案

此实现并不安全。最后一个参数可能会在您没有注意到的情况下发生变化,因为 pthread_create 不会立即创建线程。它会在某个时候执行此操作,但那时您的本地参数可能已经更改。

作为示例,尝试运行以下代码:

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

void* worker(void *arg) {
  int val = *((int*)arg);
  printf("% 5d", val);
  return arg;
}

int main() {
  pthread_t thid;
  pthread_attr_t attr;

    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

    int n = 200;
    int x = 0;
    for(x = 0; x < n; ++x) {
      pthread_create(&thid, &attr, worker, &x);
    }
  sleep(2);
  printf("\n========\n");
}

并检查会发生什么。

由 P. Czarnik 编写的代码

关于c - pthread_create 是否从指针复制参数值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29571404/

相关文章:

c - 如何编写一个宏来访问 C 中内存中的数据?

您可以使用 cv CalibrateCamera 来查找两个相机之间的外部关系吗?

c - 递归函数和pthreads

c,pthread_create 给出段错误?

c - 调用线程时出错: expected 'void * (*)(void *)' but argument is of type

c - Lua - lua_tostring() 返回奇怪的结果

在 C 中检查可用的堆栈大小

c++ - 使用 libpcap 中断捕获的问题

c - LP线程 : Pointer to a structure or address of a structure?

C 程序没有给出正确的输出