I have been trying to learn pthreads, with mutex and cond, but I can't figure out how to reset a varible ONLY after the last thread that used it doesn't need it anymore.
I have the following code:
int i = 0;
pthread_mutex_t mutex;
pthread_cond_t cond;
int test() {
if (i == 0) {
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
}
pthread_mutex_lock(&mutex);
++i;
if (i % 5 != 0) {
pthread_cond_wait(&cond, &mutex);
}
else {
pthread_cond_broadcast(&cond);
}
int j = i;
i = 0; /* problem line */
pthread_mutex_unlock(&mutex);
//i = 0; /* tried here too */
return j;
}
I have multiple threads calling this test()
method.
The first 4 threads will wait until the 5th is called, and then all 5 threads will return 5
. But the 6th+ will return '6','7',... etc, I want to reset the i variable i = 0
, so the count will restart.
I thought of doing another thread_cond_t to make the threads wait until all j = i
are finished. But I don't think that is right (or at least unnecesary).
The actual output is (undetermined order because of threads):
0
0
0
0
5
0
0
0
5
I want them all be 5
s.
Edit: I made j
global and i
is modified after the broadcast and it has worked so far:
int i = 0, j;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int test() {
pthread_mutex_lock(&mutex);
++i;
if (i % 5 != 0) {
pthread_cond_wait(&cond, &mutex);
} else {
pthread_cond_broadcast(&cond);
j = i;
}
i = 0;
pthread_mutex_unlock(&mutex);
return j;
}
This code successfully resets the variable after reaching 5, and prints that value on all threads, but it seems I suffer from dataraces when I try many threads.