作者:手机用户2502875603 | 来源:互联网 | 2023-05-17 05:25
1。 互斥量
Linux提供了控制线程执行和访问代码临界区域的方法。其中最基本的两种办法是信号量和互斥量。
关于信号量,笔者在
Linux信号量介绍中介绍
本文只介绍semaphore.h 相关的信号量的简单的操作。关于信号量在笔者其他博客里有详细介绍。
Linux还有其他共享内存的方法。
2. 与互斥量相关的函数
#
include
<pthread.h
>
int pthread_mutex_init(pthread_mutex_t
*mutex, pthread_mutexattr_t
*mutexattr);
//创建互斥量
int pthread_mutex_lock(pthread_mutex_t
*mutex);
//加锁
int pthread_mutex_unlock(pthread_mutex_t
*mutex);
//解锁
int pthread_mutex_destroy(pthread_mutex_t
*mutex);
//清理互斥量
3. 一个简单的程序例子
/***************************************
* @file mutex.c
* @brief 互斥锁
* @author Windeal
* @date 2013/08/06
***************************************/
#
include
<stdlib.h
>
#
include
<stdio.h
>
#
include
<unistd.h
>
#
include
<string.h
>
#
include
<pthread.h
>
#
define WORK_SIZE
1024
char work_area[WORK_SIZE];
pthread_mutex_t work_mutex;
int time_to_exit
=
0;
void
*thread_function(
void
*arg);
int main(
int argc,
char
* argv[])
{
int ret;
pthread_t a_thread;
void
*thread_result;
ret
= pthread_mutex_init(
&work_mutex, NULL);
if (ret
!=
0) {
perror(
"pthread_mutex_init failed\n");
exit(EXIT_FAILURE);
}
printf(
"It time to create a thread!\n");
/////////////////////
ret
= pthread_create(
&a_thread, NULL, thread_function, NULL);
if (ret
!=
0) {
perror(
"Thread creation failed!\n");
exit(EXIT_FAILURE);
}
pthread_mutex_lock(
&work_mutex);
//加锁
printf(
"Input some text. Enter \"end\" to finished\n");
while (
!time_to_exit) {
//
fgets(work_area, WORK_SIZE, stdin);
pthread_mutex_unlock(
&work_mutex);
// 解锁
while (
1) {
pthread_mutex_lock(
&work_mutex);
//加锁
if (work_area[
0]
!=
'\0'){
//如果有数据则到解锁,没有数据则继续输入
pthread_mutex_unlock(
&work_mutex);
// 解锁 因为workarea里有数据
//因此到另一个线程里比对
sleep(
1);
}
else {
break;
}
}
}
pthread_mutex_unlock(
&work_mutex);
// 解锁
printf(
"Waiting for thread finish!\n");
/////////////////
ret
= pthread_join(a_thread,
&thread_result);
if (ret
!=
0) {
perror(
"Thread finished failed\n");
exit(EXIT_FAILURE);
}
printf(
"Thread joined\n");
pthread_mutex_destroy(
&work_mutex);
exit(EXIT_SUCCESS);
}
void
*thread_function(
void
* arg) {
sleep(
1);
pthread_mutex_lock(
&work_mutex);
while (strncmp(
"end", work_area,
3)
!=
0) {
printf(
"You have enter %d charactor\n", strlen(work_area)
-
1);
work_area[
0]
=
'\0';
//清零数据区
pthread_mutex_unlock(
&work_mutex);
//让主线程继续输入数据
sleep(
1);
pthread_mutex_lock(
&work_mutex);
//尝试加锁,如果主线程已输入数据,则加锁成功
while (work_area[
0]
==
'\0') {
//如果输入为空,则继续等待输入.输入不为空时,跳出循环
pthread_mutex_unlock(
&work_mutex);
sleep(
1);
pthread_mutex_lock(
&work_mutex);
}
}
time_to_exit
=
1;
work_area[
0]
=
'\0';
pthread_mutex_unlock(
&work_mutex);
pthread_exit(
0);
}
结果如下所示: