小编MoC*_*deh的帖子

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

我是多线程的新手,而且总体来说并不是 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 = …
Run Code Online (Sandbox Code Playgroud)

c multithreading operating-system mutex pthreads

0
推荐指数
1
解决办法
72
查看次数

标签 统计

c ×1

multithreading ×1

mutex ×1

operating-system ×1

pthreads ×1