I would like to implement a multithreading process which is in charge of launching threads in parallel.
According to htop's output, each thread consumes less than 1% CPU but the main consumes around 100% CPU.
int main (int argc, char *argv[])
{
struct sigaction action;
int i;
exitReq = 0;
memset(&engine, 0, sizeof(stEngine_t));
engine.NbTasks = 12;
engine.TaskThread = malloc(engine.NbTasks * sizeof(stTask_t));
/* NbTasks = 12 */
for (i = 0; i < engine.NbTasks; i++) {
engine.TaskThread[i] = array[i];
engine.TaskThread[i].initTask();
pthread_create(&engine.TaskThread[i].tId, NULL, my_handler, (void *) &engine.TaskThread[i]);
}
while (!exitReq) {
//.. do stuff as reading external value (if value < limit => exitReq = 1)
sched_yield();
}
for (i = 0; i < engine.NbTasks; i++) {
(void)pthread_cancel(engine.TaskThread[i].tId);
pthread_join(engine.TaskThread[i].tId, NULL);
engine.TaskThread[i].stopTask();
engine.TaskThread[i].tId = 0;
}
free(engine.TaskThread);
memset(&engine, 0, sizeof(stEngine_t));
return 0;
}
static void* my_handler(void* params)
{
stTask_t* ptask = (stTask_t*) params;
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
while (!exitReq) {
ptask->launchTask();
pthread_testcancel();
}
pthread_exit(NULL);
}
The sched_yield man page says "sched_yield() causes the calling thread to relinquish the CPU.", that's why it has been used inside the loop.
I probably misunderstood something about the sched_yield() function, but is there a better and more reliable way to relinquish the CPU in this specific situation.