#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include < pthread.h>//Include line libraries # include <sema Phore.h>//contains semaphore library void *thread_functio N (void *arg); Define thread function prototype pthread_mutex_t Work_mutex; Defines the mutex number # work_size 1024char work_area[work_size]; Defines the public memory space int time_to_exit = 1; Used to control the loop int main () {int res; pthread_t A_thread; Used to save the return value of the creation thread void *thread_result; The return value for the receive thread end is res = Pthread_mutex_init (&work_m Utex, NULL); Create and initialize Mutex if (res! = 0) {// Determines whether the mutex creation succeeded Perror ("Initialize mutex failed"); Exit (Exit_failure); } res = pthread_create (&a_thread, NULL, thread_function, NULL); Create thread if (res! = 0) {//Judge create thread Whether there is an error perror ("Thread creation failed"); Exit (Exit_failure); } pthread_mutex_lock (&work_mutex); Lock Mutex ("Enter the information to be transmitted, enter ' end ' to exit \ n"); while (time_to_exit) {//Judgment Loop Flag Status Fgets (Work_area, Work_size, stdin); Pick upReceive input information Pthread_mutex_unlock (&WORK_MUTEX); Unlock mutex while (1) {pthread_mutex_lock (&work_mutex); Lock Mutex if (work_area[0]! = ' + ') {//Judge public Whether the total memory space is empty pthread_mutex_unlock (&work_mutex); Unlock the mutex amount sleep (1); The original wired path sleeps 1 seconds} else {break; End Loop}}} pthread_mutex_unlock (&work_mutex); Unlock the mutex ("\ n wait for thread to end ... \ n"); res = Pthread_join (A_thread, &thread_result); Wait for thread to end if (res! = 0) { Determine if the end thread has error perror ("Thread end Failed"); Exit (Exit_failure); } printf ("Thread end \ n"); Pthread_mutex_destroy (&work_mutex); Clears the mutex exit (exit_success);} void *thread_function (void *arg)//define thread function details {SLE EP (1); Child thread sleeps 1 seconds pthread_mutex_lock (&work_mutex); Lock semaphore while (strncmp ("End", Work_area, 3)! = 0) {//To determine if the received message is "end" printf ("received%d characters \ n", strlen (Work_area)-1); Work_area[0] = ' + '; Clear the Public Space Pthread_mutex_unlock (&work_mutex); Unlock the mutex amount sleep (1); Child thread sleeps 1 seconds pthread_mutex_lock (&work_mutex); Determine if the public space is empty while (work_area[0] = = ' + ') {Pthread_mutex_unlock (&work_mutex); Unlock the mutex amount sleep (1); Child thread sleeps 1 seconds pthread_mutex_lock (&work_mutex); Lock Mutex}} time_to_exit = 0; Set loop end flag to 0 work_area[0] = ' + '; Clear public Space Pthread_mutex_unlock (&work_mutex); Unlock mutex pthread_exit (0); End Thread}
Synchronization between threads--using mutex to achieve