简体   繁体   中英

Is a delay necessary when creating threads in a loop using pthreads in C?

I am currently writing a simple code in C using pthreads. All it does is creates 2 threads and each thread adds up one half of an array of integers in order to obtain the overall sum of the array. However, for some reason whenever I run the code without a delay between the thread creation, the second half of the array is added twice. Adding a minimal delay fixes the problem but I am curious as to why its happening. Here is the code I use to create the threads:

for(i = 0; i < THREAD_NUM; ++i){
    args.thread_num = i;
    if(pthread_create(&threads[i], NULL, getSum, (void *)&args) != 0)
      printf("Can't create thread\n");
    //usleep(1);
  }

The numbers I add are the numbers 0 through 7 and I expect the sum to be 28. But for some reason, without the delay the answer is 44 which is the sum of the numbers 4 through 7 added twice, in other words the second half of the array. With the usleep uncommented, the answer is 28. Can someone provide insight into what is happening. Thank you.

You're passing over &args to the newly-created thread, but then on the next iteration you immediately modify it and try to start another thread. What if the previous thread tries to read thread_num after this modification? It'll read the wrong value.

Definitely don't add an arbitrary sleep. That's never the right way to fix threading bugs.

Instead, here, you should stop using the same args for every single thread. Create a separate one for each thread so they don't share data. You don't show how you allocate it but it could look something like this:

struct args args[THREAD_NUM];

for (i = 0; i < THREAD_NUM; ++i) {
    args[i].thread_num = i;
    if (pthread_create(&threads[i], NULL, getSum, &args[i]) != 0) {
        printf("Can't create thread\n");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM