C 多线程 | for 循环中的线程创建使用上次迭代中的参数

MoC*_*deh 0 c multithreading operating-system mutex pthreads

我是多线程的新手,而且总体来说并不是 C 语言中最好的,所以对我来说就这样了。

我有一个 for 循环,它创建了许多线程,我将参数传递给这些线程:

  for(int i = 0; i < NO_OF_THREADS; i++) {

    int ordered_product = (rand() % NO_OF_PRODUCTS);
    int ordered_quantity = (rand() % 10) + 1;
    int customer = (rand() % NO_OF_CUSTOMERS);

    printf("%d %d %d\n", customer+1, ordered_quantity, ordered_product+1);

    ThreadArgs myargs = {customer, ordered_product, ordered_quantity};

    int rc = pthread_create(&mythreads[i], NULL, thread_function, &myargs);
    if(rc != 0) {
      perror("Pthread create");
      exit(1);
    }

  }
Run Code Online (Sandbox Code Playgroud)

我有一个函数“thread_function”,它是这样写的:

void* thread_function(void* arg) {

  ThreadArgs* args = (ThreadArgs*) arg;
  ThreadArgs myargs = *args;
  int customer_id = myargs.customer_id + 1;
  int product_quantity = myargs.product_quantity;
  int product_id = myargs.product_id +1;

  printf("Customer %d purchased %d of Product %d\n", customer_id, product_quantity, product_id);

  //pthread_exit(NULL)   // I tried this too...
  return NULL;
}
Run Code Online (Sandbox Code Playgroud)

这是我得到的输出:

4 8 4
3 3 9
8 1 9
Customer 8 purchased 1 of Product 9
Customer 8 purchased 1 of Product 9
Customer 8 purchased 1 of Product 9
Run Code Online (Sandbox Code Playgroud)

每个线程都应该打印出其各自的参数,但相反,所有三个线程都打印了最后一次迭代的参数。

由于某种原因,如果我在 for 循环的底部添加 sleep() 调用,但我不希望它休眠,问题就会消失。

将不胜感激任何帮助。

ike*_*ami 5

myargs只存在到创建它的块的末尾。当循环结束时,它不再存在,并且访问它是未定义的行为。

\n

由于变量在创建线程后立即不再存在,因此线程中运行的代码在变量不再存在后尝试访问该变量,因此具有未定义的行为。

\n

一种解决方案是延长变量的生命周期。

\n
ThreadArgs myargs[ NO_OF_PRODUCTS ];\n\nfor ( int i = 0; i < NO_OF_THREADS; ++i ) {\n   \xe2\x80\xa6\n   myargs[i].\xe2\x80\xa6 = \xe2\x80\xa6;\n   \xe2\x80\xa6\n   pthread_create( mythreads+i, NULL, thread_function, myargs+i )\n   \xe2\x80\xa6\n}\n
Run Code Online (Sandbox Code Playgroud)\n

另一种方法是使用malloc分配结构。

\n

另一个方法是确保线程在继续之前已获取并复制了数据,这可以通过某种形式的同步来完成。

\n