Sponsored Content
Top Forums Programming How to sleep and wake a thread??? Post 302582588 by Corona688 on Friday 16th of December 2011 12:04:40 PM
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);
}

 

7 More Discussions You Might Find Interesting

1. 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

2. 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

3. 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

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. 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

6. 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

7. 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
PTHREAD_MUTEXATTR_SETROBUST(3)				     Linux Programmer's Manual				    PTHREAD_MUTEXATTR_SETROBUST(3)

NAME
pthread_mutexattr_getrobust, pthread_mutexattr_setrobust - get and set the robustness attribute of a mutex attributes object SYNOPSIS
#include <pthread.h> int pthread_mutexattr_getrobust(const pthread_mutexattr_t *attr, int *robustness); int pthread_mutexattr_setrobust(const pthread_mutexattr_t *attr, int robustness); Compile and link with -pthread. Feature Test Macro Requirements for glibc (see feature_test_macros(7)): pthread_mutexattr_getrobust(), pthread_mutexattr_setrobust(): _POSIX_C_SOURCE >= 200809L DESCRIPTION
The pthread_mutexattr_getrobust() function places the value of the robustness attribute of the mutex attributes object referred to by attr in *robustness. The pthread_mutexattr_setrobust() function sets the value of the robustness attribute of the mutex attributes object referred to by attr to the value specified in *robustness. The robustness attribute specifies the behavior of the mutex when the owning thread dies without unlocking the mutex. The following values are valid for robustness: PTHREAD_MUTEX_STALLED This is the default value for a mutex attributes object. If a mutex is initialized with the PTHREAD_MUTEX_STALLED attribute and its owner dies without unlocking it, the mutex remains locked afterwards and any future attempts to call pthread_mutex_lock(3) on the mutex will block indefinitely. PTHREAD_MUTEX_ROBUST If a mutex is initialized with the PTHREAD_MUTEX_ROBUST attribute and its owner dies without unlocking it, any future attempts to call pthread_mutex_lock(3) on this mutex will succeed and return EOWNERDEAD to indicate that the original owner no longer exists and the mutex is in an inconsistent state. Usually after EOWNERDEAD is returned, the next owner should call pthread_mutex_consistent(3) on the acquired mutex to make it consistent again before using it any further. If the next owner unlocks the mutex using pthread_mutex_unlock(3) before making it consistent, the mutex will be permanently unus- able and any subsequent attempts to lock it using pthread_mutex_lock(3) will fail with the error ENOTRECOVERABLE. The only permit- ted operation on such a mutex is pthread_mutex_destroy(3). If the next owner terminates before calling pthread_mutex_consistent(3), further pthread_mutex_lock(3) operations on this mutex will still return EOWNERDEAD. Note that the attr argument of pthread_mutexattr_getrobust() and pthread_mutexattr_setrobust() should refer to a mutex attributes object that was initialized by pthread_mutexattr_init(3), otherwise the behavior is undefined. RETURN VALUE
On success, these functions return 0. On error, they return a positive error number. In the glibc implementation, pthread_mutexattr_getrobust() always return zero. ERRORS
EINVAL A value other than PTHREAD_MUTEX_STALLED or PTHREAD_MUTEX_ROBUST was passed to pthread_mutexattr_setrobust(). VERSIONS
pthread_mutexattr_getrobust() and pthread_mutexattr_setrobust() were added to glibc in version 2.12. CONFORMING TO
POSIX.1-2008. NOTES
In the Linux implementation, when using process-shared robust mutexes, a waiting thread also receives the EOWNERDEAD notification if the owner of a robust mutex performs an execve(2) without first unlocking the mutex. POSIX.1 does not specify this detail, but the same behav- ior also occurs in at least some other implementations. Before the addition of pthread_mutexattr_getrobust() and pthread_mutexattr_setrobust() to POSIX, glibc defined the following equivalent nonstandard functions if _GNU_SOURCE was defined: int pthread_mutexattr_getrobust_np(const pthread_mutexattr_t *attr, int *robustness); int pthread_mutexattr_setrobust_np(const pthread_mutexattr_t *attr, int robustness); Correspondingly, the constants PTHREAD_MUTEX_STALLED_NP and PTHREAD_MUTEX_ROBUST_NP were also defined. These GNU-specific APIs, which first appeared in glibc 2.4, are nowadays obsolete and should not be used in new programs. EXAMPLE
The program below demonstrates the use of the robustness attribute of a mutex attributes object. In this program, a thread holding the mutex dies prematurely without unlocking the mutex. The main thread subsequently acquires the mutex successfully and gets the error EOWN- ERDEAD, after which it makes the mutex consistent. The following shell session shows what we see when running this program: $ ./a.out [original owner] Setting lock... [original owner] Locked. Now exiting without unlocking. [main thread] Attempting to lock the robust mutex. [main thread] pthread_mutex_lock() returned EOWNERDEAD [main thread] Now make the mutex consistent [main thread] Mutex is now consistent; unlocking Program source #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <pthread.h> #include <errno.h> #define handle_error_en(en, msg) do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0) static pthread_mutex_t mtx; static void * original_owner_thread(void *ptr) { printf("[original owner] Setting lock... "); pthread_mutex_lock(&mtx); printf("[original owner] Locked. Now exiting without unlocking. "); pthread_exit(NULL); } int main(int argc, char *argv[]) { pthread_t thr; pthread_mutexattr_t attr; int s; pthread_mutexattr_init(&attr); /* initialize the attributes object */ pthread_mutexattr_setrobust(&attr, PTHREAD_MUTEX_ROBUST); /* set robustness */ pthread_mutex_init(&mtx, &attr); /* initialize the mutex */ pthread_create(&thr, NULL, original_owner_thread, NULL); sleep(2); /* "original_owner_thread" should have exited by now */ printf("[main thread] Attempting to lock the robust mutex. "); s = pthread_mutex_lock(&mtx); if (s == EOWNERDEAD) { printf("[main thread] pthread_mutex_lock() returned EOWNERDEAD "); printf("[main thread] Now make the mutex consistent "); s = pthread_mutex_consistent(&mtx); if (s != 0) handle_error_en(s, "pthread_mutex_consistent"); printf("[main thread] Mutex is now consistent; unlocking "); s = pthread_mutex_unlock(&mtx); if (s != 0) handle_error_en(s, "pthread_mutex_unlock"); exit(EXIT_SUCCESS); } else if (s == 0) { printf("[main thread] pthread_mutex_lock() unexpectedly succeeded "); exit(EXIT_FAILURE); } else { printf("[main thread] pthread_mutex_lock() unexpectedly failed "); handle_error_en(s, "pthread_mutex_lock"); } } SEE ALSO
get_robust_list(2), set_robust_list(2), pthread_mutex_init(3), pthread_mutex_consistent(3), pthread_mutex_lock(3), pthreads(7) Linux 2019-03-06 PTHREAD_MUTEXATTR_SETROBUST(3)
All times are GMT -4. The time now is 09:13 PM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy