Skip to content

Instantly share code, notes, and snippets.

@Hotshot824
Created December 21, 2023 05:59
Show Gist options
  • Save Hotshot824/696bc2c9bede5a64a13f3e330a51c34b to your computer and use it in GitHub Desktop.
Save Hotshot824/696bc2c9bede5a64a13f3e330a51c34b to your computer and use it in GitHub Desktop.
signal-wait-adptive-mutex.c
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
pthread_mutex_t mutex;
sem_t semaphore1, semaphore2;
pthread_mutexattr_t attr;
pthread_t id1, id2;
int gotoSleep = 0;
void p(void *para)
{
for (int i = 0; i < 100; i++)
{
pthread_mutex_lock(&mutex);
sem_post(&semaphore1);
if (gotoSleep)
usleep(1);
pthread_mutex_unlock(&mutex);
sem_wait(&semaphore2);
}
}
void q(void *para)
{
for (int i = 0; i < 100; i++)
{
sem_wait(&semaphore1);
pthread_mutex_lock(&mutex);
pthread_mutex_unlock(&mutex);
sem_post(&semaphore2);
}
}
int main(int argc, char **argv)
{
for (int i = 0; i < argc; i++)
{
if (strcmp(argv[i], "-s") == 0)
{
gotoSleep = 1;
}
}
sem_init(&semaphore1, 0, 0);
sem_init(&semaphore2, 0, 0);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ADAPTIVE_NP);
pthread_mutex_init(&mutex, &attr);
pthread_create(&id1, NULL, (void *)p, NULL);
pthread_create(&id2, NULL, (void *)q, NULL);
pthread_join(id1, NULL);
pthread_join(id2, NULL);
pthread_mutex_destroy(&mutex);
pthread_mutexattr_destroy(&attr);
sem_destroy(&semaphore1);
sem_destroy(&semaphore2);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment