linux基础编程—互斥锁
Posted CPP开发之家
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了linux基础编程—互斥锁相关的知识,希望对你有一定的参考价值。
互斥意味着具有“排它性”,即两个线程不能同时进入被互斥保护的代码。Linux下可以通过pthread_mutex_t 定义互斥体机制完成多线程的互斥操作,该机制的作用是对某个需要互斥的部分,在进入时先得到互斥体,如果没有得到互斥体,表明互斥部分被其它线程拥有,此时欲获取互斥体的线程阻塞,直到拥有该互斥体的线程完成互斥部分的操作为止。 互斥量的操作函数包括:
#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 <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <semaphore.h>
#define SIZE 1024
char buffer[SIZE];
void *thread_function(void *arg);
pthread_mutex_t mutex;
int main()
{
int res;
pthread_t a_thread;
void *thread_result;
res = pthread_mutex_init(&mutex, NULL);
if (res != 0)
{
perror("Mutex init failed!");
exit(EXIT_FAILURE);
}
res = pthread_create(&a_thread, NULL, thread_function, NULL);
if (res != 0)
{
perror("Thread create failed!");
exit(EXIT_FAILURE);
}
printf("Input some text. Enter 'end' to finish/n");
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(a_thread, &thread_result);
if (res != 0)
{
perror("Thread join failed!");
exit(EXIT_FAILURE);
}
printf("Thread joined/n");
pthread_mutex_destroy(&mutex);
exit(EXIT_SUCCESS);
}
void *thread_function(void *arg)
{
sleep(1);
while (1)
{
pthread_mutex_lock(&mutex);
printf("You input %d characters/n", strlen(buffer));
pthread_mutex_unlock(&mutex);
if (strncmp("end", buffer, 3) == 0)
break;
sleep(1);
}
}
以上是关于linux基础编程—互斥锁的主要内容,如果未能解决你的问题,请参考以下文章