Reputation: 1
I am trying to find an easy way to sleep or stop executing, and wake another (so not the calling ) thread in C. It shoud work like this:
int main(void)
{
int msg = 0;
ptread_t t;
pthread_create(&t, NULL, work, NULL)
while(1)
{
msg = receive_msg();
switch(msg)
case 1:
//sleep_pthread(t);
break;
case 2:
//wake_pthread(t);
break;
default:
break;
}
}
void work(void)
{ //do whatever it needs to
}
receive_msg() waits for a user action so I don't know how much time I have to stop the thread from execution. Where I need help is which functions should I use for those sleep_pthread(t); and wake_pthread(t); parts.
Upvotes: 0
Views: 705
Reputation: 671
From what you are saying "find an easy way to sleep or stop executing, and wake another (so not the calling ) thread in C" - your requirement seems to suggest you need simple pthread_cond_wait or pthread_cond_timedwait to satisfy your needs. By using them you are forcing them to go into sleep state till condition is not satisfied or timer expires.
Below is sample code
#include <pthread.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define WAIT_TIME_SECONDS 15
typedef struct mystruct_tag
{
pthread_mutex_t mutex;
pthread_cond_t cond;
int value;
} mystruct_t;
mystruct_t data = {PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, 0};
/*
* thread start routine. It will set the main thread's predicate and
* signal the condition variable
*/
void *wait_thread (void *arg)
{
int status;
long sleep_time = (long)arg;
status = pthread_mutex_lock(&data.mutex);
if (status != 0)
{
printf(" failed \n");
}
sleep(sleep_time);
data.value = 1; /*set predicate */
status = pthread_cond_signal (&data.cond);
if (status != 0)
{
printf(" failed at condition \n");
}
status = pthread_mutex_unlock (&data.mutex);
return NULL;
}
int main (void)
{
int status;
pthread_t wait_thread_id;
struct timespec timeout;
struct timeval tp;
pthread_create(&wait_thread_id, NULL, wait_thread, (void *)50);
timeout.tv_sec = tp.tv_sec;
timeout.tv_nsec = 0;
timeout.tv_sec += WAIT_TIME_SECONDS;
pthread_mutex_lock(&data.mutex);
while(data.value == 0)
{
pthread_cond_timedwait (&data.cond, &data.mutex, &timeout); /*can use cond_wait too instead of timedwait*/
}
status = pthread_mutex_unlock(&data.mutex);
return 0;
}
Upvotes: 1
Reputation: 62583
You can not sleep nor wake the thread from the outside. Moreover, any design which requires this functionality is broken. Why do you need to just turn the thread to sleep? What you need is a proper synchronization points betyween threads, so that thread will simply wait when there is no work for it to be done.
Upvotes: 0