Get the App
SLTechnology News&Howtos  ›  Servers  › 

Application example of unix mutex and semaphore

Shulou Source: shulou.com Published: 2022-06-02 14:24:38 10月16日 Update

# include#include # define SIZE 3#define STR_SIZE 20pthread_mutex_t mutex; / / Global variables can be seen in sem_t read_sem for main and thread functions, and write_sem; / / global variables can be seen for main and thread functions as struct _ buf_ {char* buf [SIZE]; int front, rear;} buffer / / cyclic queue structure void thread (void) {while (1) {if (0! = sem_wait (& read_sem)) {perror ("sem_wait_0"); exit (1);} if (0! = pthread_mutex_lock (& mutex)) {perror ("pthread_mutex_lock_0"); exit (1);} fputs ("output characters:\ n", stdout); fputs (buffer.buf [buffer.front], stdout); buffer.front = (buffer.front + 1)% SIZE If (0! = pthread_mutex_unlock (& mutex)) {perror ("pthread_mutex_lock_0"); exit (1);} if (0! = sem_post (& write_sem)) {perror ("sem_wait_0"); exit (1);} sleep (10);}} int main (void) {/ / initialize the circular queue structure int iscape bufferbuffer.front = buffer.rear = 0x bufferbuffer.I

Tags: Signals threads semaphores global functions parameters variables structures queues loops blocking two characters data files standards processes attachments inputs examples Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information Microsoft MySQL vpn OPPO Reno