创建互斥锁
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER
pthread_mutex_init(&mutex, NULL)
销毁互斥锁
pthread_mutex_destroy
上锁
pthread_mutex_lock
阻塞式pthread_mutex_trylock
非阻塞式解锁
pthread_mutex_unlock
阻塞式练习
#include <stdio.h>
#include <pthread.h>
#include <errno.h>
#include <signal.h>
#include <unistd.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <sys/ipc.h>
#include <stdlib.h>
pthread_mutex_t mutex;
void printer(char *str) {
pthread_mutex_lock(&mutex);
while(*str != '\\0') {
putchar(*str);
fflush(stdout);
str++;
sleep(1);
}
printf("\\n");
pthread_mutex_unlock(&mutex);
}
void *thread1_fun(void *arg) {
char *str = "hello";
printer(str);
}
void *thread2_fun(void *arg) {
char *str = "world";
printer(str);
}
int main(int argc, char** argv) {
pthread_t thread1, thread2;
pthread_mutex_init(&mutex, NULL);
pthread_create(&thread1, NULL, thread1_fun, NULL);
pthread_create(&thread2, NULL, thread2_fun, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;c
}