Skip to content

Instantly share code, notes, and snippets.

@time-river
Created September 6, 2021 01:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save time-river/55745d01664ba125e5fb94aca3d250a2 to your computer and use it in GitHub Desktop.
Save time-river/55745d01664ba125e5fb94aca3d250a2 to your computer and use it in GitHub Desktop.
#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