I wrote this program that's supposed create a new thread in every iteration of the main loop and have it print the iteration variable. Eg. in the first iteration, a new thread is made and it should print "arg: 0", next iteration prints "arg: 1", etc.
As you can see in the screenshot below, arg 3 & 7 are being printed twice, while it should only print once. Now it works if I add sleep(1) to every iteration, so it's some kind of concurrency issue. Note that the result is completely random every time, it's not just 3 and 7 every time.
Anyone have an idea? Thanks!
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
static void * mutex_thread(void * arg);
int threads_amt = 10;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int main (void)
{
pthread_t threads[threads_amt];
// Create threads.
for(int i = 0; i < threads_amt; i++)
{
printf ("Starting thread [%d]...\n", i);
// Create thread.
pthread_create (&threads[i], NULL, mutex_thread, &i);
// IT WORKS IF I ENABLE sleep(1).
//sleep (1);
printf ("Thread created.\n\n");
}
// Join threads.
printf("Joining threads...\n");
for(int i = 0; i < threads_amt; i++)
{
pthread_join (threads[i], NULL);
}
return (0);
}
static void * mutex_thread(void * arg)
{
// Lock mutex.
pthread_mutex_lock (&mutex);
// Print arg.
int *number = (int*)arg;
printf("arg: %d\n", *number);
// Unlock mutex.
pthread_mutex_unlock (&mutex);
return (NULL);
}
You have data race - because you are passing the same address (of variable i
) to all the threads.
Pass a different address (for example use an array or use a `malloc'ed value) to each thread.
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.