Visit Our UNIX and Linux User Community


How to sleep and wake a thread???


 
Thread Tools Search this Thread
Top Forums Programming How to sleep and wake a thread???
# 1  
Old 12-16-2011
How to sleep and wake a thread???

Hi guys,
I am creating two posix threads. I have some queries, hopefully you will help me out with them
1) How can I put a thread to indefinite sleep, for indefinite time period. I am familiar with this
Code:
sleep(5);

for 5 second, how can I make it indefinite??
2) How can one thread wake another sleeping thread
3) Can one thread force another thread to go to sleep

Here is the program which is really bothering me, the idea is to have two threads, one filling the stack, and one emptying it. But I can't have one of my thread to wake up the other, after the stack is empty or full
See it for yourself!

Code:
 
#include <stdio.h>
#include <stdlib.h>
#include <curses.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#define MAX_SIZE 10
int Counter;
struct Stack
{
 int home[MAX_SIZE];
 int top;
};
struct Stack s;
void InitStack(struct Stack *s)
{
 s->top = -1;
 Counter = 0;
}
void Push(struct Stack *s, int x)
{
 if(s->top == MAX_SIZE-1)
 {
  printf("Stack is full!\n");
  exit(0);
 }
 else
 s->top++;
 s->home[s->top] = x;
 Counter++;
 printf("Counter = %d\n", Counter);
}
void Pop(struct Stack *s)
{
 int y;
 if(s->top == -1)
 {
  printf("Stack empty!\n");
  exit(0);
 }
 else
 y = s->home[s->top];
 s->top--;
 printf("%d poped\n",y);
 Counter--;
 printf("Counter = %d\n", Counter);
}

void *threadA(void *);
void *threadB(void *);
int main()
{
 InitStack(&s); 
 int i, j, k;
 pthread_t tid[2];
 pthread_attr_t attr[2];
 for(i=1;i<=2;i++)
 {
  pthread_attr_init(&attr[i-1]);
 }
  {
  pthread_create(&tid[0],&attr[0],threadA,(void *)786);
  pthread_create(&tid[1],&attr[1],threadB,(void *)786);
  }
 { 
 pthread_join(tid[0],NULL);
 pthread_join(tid[1],NULL);
 }
return 0;
}

void *threadA(void *n)
{
 int x;
 x = (int)n;
 while(1) 
 {
 if(Counter != MAX_SIZE)
 {
 Push(&s,x);
 printf("x = %d\n", x);
 sleep(1);
 }
 else
 {
 printf("Going for a long sleep as Stack is full!\n");
 sleep(50);
 }
 }
}
void *threadB(void *n)
{
 int x;
 sleep(15);
 while(1)
 {
 if(Counter != 0)
 {
 Pop(&s);
 sleep(1);
 }
 else
 {
 printf("Going for a long sleep as Stack is empty!\n");
 sleep(50);
 }
 }
}


If you can explain your points with a very small program, that would be so so nice of you.
Desperately waiting for your wonderful replies!!!!

Thanks alot in advance!

Last edited by gabam; 12-16-2011 at 10:18 AM..
# 2  
Old 12-16-2011
You can sleep "indefinitely" with the pause() function, defined in <unistd.h>, which will sleep until you receive a signal.

You can wake a pause()d thread with pthread_kill() to send some signal that won't kill it (SIGCONT seems appropriate).

Though if you're expecting threads to cooperate, you should look into conditions and mutexes.
# 3  
Old 12-16-2011
As John said above, you probably want your thread to block not sleep. Calls like sleep send SIGALRM to the calling process, not just the thread. This means that you have to set up signal handling for the thread in question, and have all the other threads ignore
SIGALRM (example only, there are other signals)

Using a condition wait or a mutex wait is much more efficient.
# 4  
Old 12-16-2011
Looks like you have a typical synchronization problem. One such you would like to use conditional variables to solve. Have a look at pthread_cond_wait, pthread_cond_signal, mutexes and related stuff.
# 5  
Old 12-16-2011
Could you please write a small little program to show how these functions work, I beg you please!
Thanks!
# 6  
Old 12-16-2011
Try googling for examples.

Oh, and:

Quote:
3) Can one thread force another thread to go to sleep
Not by any mechanism that I know of.
# 7  
Old 12-16-2011
Code:
#include <pthread.h>
#include <stdio.h>

// Simplest way to create a mutex, no function calls needed
pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;

// When two threads must use the same memory, you must use
// mutex calls to make it safe.  It's not just a lock, it's also a
// "memory barrier", guaranteeing memory values between different CPU cores
// are synchronized properly.
int running=1;

void *thread(void *arg)
{
        fprintf(stderr, "Thread beginning\n");
        while(1)
        {
                int r;
                fprintf(stderr, "thread waiting for lock\n");
                // If main already has the mutex, thread will sleep.
                // when main unlocks it, the thread will lock it and continue.
                pthread_mutex_lock(&lock);
                        fprintf(stderr, "We have the mutex, it is safe to get value of 'running'\n");
                        r=running;
                        fprintf(stderr, "Value of 'running' is %d\n", r);
                pthread_mutex_unlock(&lock); // What gets locked MUST be unlocked later!
                fprintf(stderr, "thread has given up the lock\n");
                if(r == 0) break;
                sleep(1);
        }
        fprintf(stderr, "thread finishing\n");

        return((void *)0xdeadbeef);
}

int main()
{
        void *ret;
        pthread_t tid;
        running=1;
        pthread_mutex_lock(&lock); // Stop thread from getting the mutex
        fprintf(stderr, "main now has the mutex\n");

        pthread_create(&tid, NULL, thread, NULL);
        sleep(2); // Thread will begin, but wait for mutex

        fprintf(stderr, "main is unlocking the mutex\n");
        pthread_mutex_unlock(&lock); // Let the thread run for a while
        sleep(5);

        // Lock the mutex, making it safe to alter 'running'
        pthread_mutex_lock(&lock);
                fprintf(stderr, "main now has the mutex\n");
                running=0;
                fprintf(stderr, "main is unlocking the mutex\n");
        pthread_mutex_unlock(&lock);

        pthread_join(tid, &ret);
        fprintf(stderr, "Thread finished with return value %p\n", ret);
}


Previous Thread | Next Thread
Test Your Knowledge in Computers #77
Difficulty: Easy
MINIX was a Unix-like operating system created for educational purposes.
True or False?

7 More Discussions You Might Find Interesting

1. UNIX for Dummies Questions & Answers

Computer wake commands

I'm a OS X user (MacBook Pro, OS X Lion) and I need it to wake up on Mondays, Wednesdays, Thursdays and Saturdays at 9:00 AM on the rest of the days of the week at 7:00 I issue the following commands: sudo pmset repeat wake MWRS 09:00:00 for the former sudo pmset repeat wake TFU... (1 Reply)
Discussion started by: scrutinizerix
1 Replies

2. UNIX for Dummies Questions & Answers

Linux Device Driver: how can an ISR wake up a user-thread?

Hi all, Is it possible to do the following in Linux (kernel 2.6.x): - A user-space thread goes to "sleep". Using any call/mechanism - On a hardware generated interrupt, the Interrupt handler (ISR) "wakes" the sleeping user-thread. I have seen wait_event() and wake_up() but it appears... (1 Reply)
Discussion started by: agaurav
1 Replies

3. Shell Programming and Scripting

Wrapping 'sleep' with my 'resleep' function (Resettable sleep)

This is a very crude attempt in Bash at something that I needed but didn't seem to find in the 'sleep' command. However, I would like to be able to do it without the need for the temp file. Please go easy on me if this is already possible in some other way: How many times have you used the... (5 Replies)
Discussion started by: deckard
5 Replies

4. UNIX for Advanced & Expert Users

wake up user space thread from kernel space ISR

Hello, I'm searching for a proper way to let the kernel space ISR(implemented in a kernel module) wake up a user space thread on a hardware interrupt. Except for sending a real-time signal, is it possible to use a semaphore? I've searched it on google, but it seems impossible to share a... (0 Replies)
Discussion started by: aaronwong
0 Replies

5. Programming

how to wake up a thread that blocking at epoll_wait?

I have two threads: one maintains a thread-safe message queue (handle this queue at the beginning of every loop) and deals with tcp connections, the other one posts message to the former one. the problem is, while the former one was blocking at epoll_wait, it's not sure that how long until the... (0 Replies)
Discussion started by: cometeor
0 Replies

6. Shell Programming and Scripting

Wake on LAN script

m old to Unix but new to scripting I have a MacBook running osx that I want to use as an nfs client. The server will be a linux box with a wake on lan card. Here's the idea. Run a cron command on the mac every minute that checks if I am on my home wireless network (the linux box is wired to... (6 Replies)
Discussion started by: anon0mus
6 Replies

7. UNIX for Advanced & Expert Users

Wake on Lan script

Im old to Unix but new to scripting I have a MacBook running osx that I want to use as an nfs client. The server will be a linux box with a wake on lan card. Here's the idea. Run a cron command on the mac every minute that checks if I am on my home wireless network (the linux box is wired to... (0 Replies)
Discussion started by: anon0mus
0 Replies

Featured Tech Videos