Created
September 6, 2021 01:43
-
-
Save time-river/55745d01664ba125e5fb94aca3d250a2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#include <signal.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <pthread.h> | |
#include <errno.h> | |
static int stop; | |
static void sighandler(int sig) { | |
fprintf(stdout, "receive signal, set flag.\n"); | |
stop = 1; | |
} | |
static void *thread_start(void *arg) { | |
pthread_mutex_t *mutex = arg; | |
if (pthread_mutex_lock(mutex) < 0) { | |
perror("%s: pthread_mutex_lock"); | |
return NULL; | |
} | |
while (stop != -1) { | |
fprintf(stdout, "thread %lx is holding the lock...\n", pthread_self()); | |
sleep(1); | |
} | |
return NULL; | |
} | |
static int mutex_init(pthread_mutex_t *mutex) { | |
pthread_mutexattr_t attr; | |
pthread_mutexattr_init(&attr); | |
pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_INHERIT); | |
pthread_mutex_init(mutex, &attr); | |
return 0; | |
} | |
int main(int argc, char *argv[]) { | |
pthread_mutex_t mutex; | |
pthread_t thread_info; | |
int retval; | |
if (signal(SIGINT, sighandler) != 0) { | |
perror("signal"); | |
return -1; | |
} | |
mutex_init(&mutex); | |
retval = pthread_create(&thread_info, NULL, thread_start, &mutex); | |
if (retval != 0) { | |
perror("pthread_create"); | |
return -1; | |
} | |
// should failed, return EINTR | |
retval = pthread_mutex_trylock(&mutex); | |
fprintf(stdout, "pthread_mutex_trylock retval %d: %s\n", retval, strerror(retval)); | |
while (stop != 1) | |
sleep(1); | |
stop = -1; | |
if (pthread_join(thread_info, NULL) < 0) { | |
perror("pthread_join"); | |
return -1; | |
} | |
// should success | |
retval = pthread_mutex_trylock(&mutex); | |
fprintf(stdout, "pthread_mutex_trylock retval %d: %s\n", retval, strerror(retval)); | |
exit(0); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment