I have created multiple threads and want to run them in a round robin fashion using condition variable and signal ( pthread_cond_wait & pthread_cond_signal).
I have used two approach , one approach is working but wasting CPU whereas other approach not working, not wasting CPU.
The problem I am facing is signal is sent before my threads waiting and the signal is lost. so it goes into infinite waiting loop.
First approach :
Threads are created and waiting for condition variable and continuously checking for a varible called as state( inside a while loop).
when state == my_id the thread with my_id got activated and it then signal to next thread my_id+1 and so on.
DRAWBACK : Wastage of CPU
Second approach :
Threads are created and waiting for signal for its own condition variable. Now as signal was already sent before thread start waiting , signal is lost and program goes into infinite wait loop.
Is there anything like "Self Signalling " or other way to send signal when signal is lost ?
I am using g++ under linux. Any clue will be highly appreciated. Thanks in advance.
Program with first approach is here round robin .
Here is my program with second approach:
#include <pthread.h>
#include <stdio.h>
#include <iostream>
#include <mutex> // std::mutex
#define MULTIPLE_THREADS 2
#define NTHREADS MULTIPLE_THREADS*64
#define NO_OF_LOOP 1
pthread_cond_t cond[NTHREADS];
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
using namespace std;
/* This is our thread function. It is like main(), but for a thread*/
void *threadA(void *arg)
{
long my_id = (long)arg;
int i = 0;
while(i < NO_OF_LOOP)
{
// Awaken or unblocked by thread (i-1)
pthread_mutex_lock(&mutex1);
pthread_cond_wait(&cond[my_id], &mutex1);
pthread_mutex_unlock(&mutex1);
printf("I am thread - %ld",my_id);
++i;
/* wake up thread i+1 */
pthread_mutex_lock(&mutex1);
pthread_cond_signal(&cond[(my_id + 1) % NTHREADS]);
pthread_mutex_unlock(&mutex1);
}
return NULL;
}
int main(void)
{
pthread_t threadid[NTHREADS];
// Initialization
for(int i=0;i<NTHREADS;i++)
cond[i]= PTHREAD_COND_INITIALIZER;
//printf("Create %d threads\n", NTHREADS);
for(long i=0; i<NTHREADS; ++i) {
pthread_create(&threadid[i], NULL, threadA, (void *)i);
//printf("Thread created=%d\n", i);
}
// printf("Wait for threads and cleanup\n");
for (long i=0; i<NTHREADS; ++i) {
pthread_join(threadid[i], NULL);
}
return 0;
}