互斥锁的基本函数和用于信号量的函数非常相似:
#include <pthread.h>
int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t, *mutexattr);
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);
int pthread_mutex_destory(pthread_mutex_t *mutex);
以下是代码实例:
#include <iostream>
#include <string>#include <pthread.h>
#include <stdio.h>
#include <semaphore.h>
using namespace std;
#define SIZE 1024
char buffer[SIZE];
void *thread_function(void *arg);
pthread_mutex_t mutex;
int main()
{
int res;
pthread_t ThreadID;
void* ThreadResult;
res = pthread_mutex_init(&mutex, NULL);
if (res != 0)
{
perror("MUTEX INIT FAILED!");
exit(EXIT_FAILURE);
}
res = pthread_create(&ThreadID, NULL, thread_function, NULL);
if (res != 0)
{
perror("Thread Create Failed!");
exit(EXIT_FAILURE);
}
printf("ThreadID:%d\n", ThreadID);
while(1)
{
pthread_mutex_lock(&mutex);
scanf("%s", buffer);
pthread_mutex_unlock(&mutex);
if (strncmp("end", buffer, 3) == 0)
{
break;
}
sleep(1);
}
res = pthread_join(ThreadID, &ThreadResult);
if (res != 0)
{
perror("Thread Join Failed");
exit(EXIT_FAILURE);
}
printf("Thread join\n");
pthread_mutex_destroy(&mutex);
return(EXIT_SUCCESS);
}
void *thread_function(void *arg)
{
sleep(1);
while(1)
{
pthread_mutex_lock(&mutex);
printf("you input %d \n", strlen(buffer));
pthread_mutex_unlock(&mutex);
if (strncmp("end", buffer, 3) == 0)
{
break;
}
sleep(1);
}
pthread_exit(NULL);
}