---
title: "POSIX线程－（四）"
author: "winzenghua"
date: "2009-07-19T15:06:00Z"
tags: []
slug: "posix"
draft: false
lastmod: "2009-07-19T15:06:00Z"
id: 948816
url: "https://java4gis.iteye.com/blog/948816"
---

**使用互斥同步**

在多线程程序中同步访问的另一个方法就是使用互斥，其作用允许程序锁住一个对象，从而只有一个线程可以访问他。要控制对临界区代码的访问，在我们进入这段代码之前锁住一个互斥量，并且在我们完成操作时进行解锁。

使用互斥所需要基本函数与信号量所需要的函数相似，其声明如下：

#include &lt;pthread.h&gt;  
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\_destroy(pthread\_mutex\_t \*mutex);

如平常一样，成功时返回0，如果失败则会返回一个错误代码，但是并没有设置errno；我们必须使用返回代码。

与信号量相类似，这些函数以一个指向前面声明的对象的指针为参数，在互斥方法是一个pthread\_mutex\_t。额外的属性参数pthread\_mutexattr\_t允许我们为互斥提供属性，这可以控制其行为。属性类型默认为"fast"。这有一个小的缺点，如果我们的程序试着在一个已经上锁的互斥量上调用pthread\_mutex\_lock，程序就会阻塞。因为拥有锁的线程现在被阻塞了，互斥量就不会被解锁，从而程序就会进入死锁状态。可以修改互斥量的属性，从而他或者可以检测这种情况并返回一个错误，或者是循环操作并且在同一个线程上允许多个锁。

设置互斥量的属性超出了本书的范围，所以我们会为属性指针传递NULL并且使用默认行为。我们可以通过阅读pthread\_mutex\_init手册页了解修改属性的内容。

**试验－－线程互斥**

再一次说明，下面的程序是我们原始程序thread1.c的修改版，但是进行了大量的修改。这一次，我们有一些偏狂来访问我们的临界变量，并且使用一个互斥量来保证每次只有一个线程访问他们。为了使得代码更易于阅读，我们忽略了由互斥量加锁与解锁操作返回值的错误检测。在生产代码中，我们应该检测这些返回值。下面是这个新程序，thread4.c：

#include &lt;stdio.h&gt;  
#include &lt;stdlib.h&gt;  
#include &lt;unistd.h&gt;  
#include &lt;string.h&gt;  
#include &lt;pthread.h&gt;  
#include &lt;semaphore.h&gt;

void \*thread\_function(void \*arg);  
pthread\_mutex\_t work\_mutex;

#define WORK\_SIZE 1024  
char work\_area\[WORK\_SIZE];  
int time\_to\_exit = 0;

int main()  
{  
int res;  
pthread\_t a\_thread;  
void \*thread\_result;  
res = pthread\_mutex\_init(&work\_mutex,NULL);  
if(res != 0)  
{  
perror("Mutex initialization failed");  
exit(EXIT\_FAILURE);  
}  
res = pthread\_create(&a\_thread,NULL,thread\_function,NULL);  
if(res != 0)  
{  
perror("Thread creation failed");  
exit(EXIT\_FAILURE);  
}  
pthread\_mutex\_lock(&work\_mutex);  
printf("Input some text, Enter 'end' to finish\\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);  
sleep(1);  
}  
else  
{  
break;  
}  
}  
}  
pthread\_mutex\_unlock(&work\_mutex);  
printf("\\nWaiting for thread to finish...\\n");  
res = pthread\_join(a\_thread,&thread\_result);  
if(res != 0)  
{  
perror("Thread join failed");  
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 input %d characters\\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);  
}

$ cc -D\_REENTRANT -I/usr/include/nptl thread4.c –o thread4 -L/usr/lib/nptl -  
lpthread  
$ ./thread4  
Input some text. Enter ‘end’ to finish  
Whit  
You input 4 characters  
The Crow Road  
You input 13 characters  
end  
Waiting for thread to finish...  
Thread joined

**工作原理**

我们开始声明了一个互斥量，我们的工作区，而且这次，我们声明了一个额外变量：time\_to\_exit。

pthread\_mutex\_t work\_mutex; /* protects both work\_area and time\_to\_exit \*/  
#define WORK\_SIZE 1024  
char work\_area\[WORK\_SIZE];  
int time\_to\_exit = 0;

然后我们初始化互斥量

res = pthread\_mutex\_init(&work\_mutex, NULL);  
if (res != 0) {  
perror(“Mutex initialization failed”);  
exit(EXIT\_FAILURE);  
}

接下来我们开始我们的新线程。下面是线程函数内部执行的代码：

pthread\_mutex\_lock(&work\_mutex);  
while(strncmp(“end”, work\_area, 3) != 0) {  
printf(“You input %d characters\\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);

首先，新线程尝试锁住这个互斥量。如果他已经被锁住了，调用就会阻塞直到互斥量被释放。一旦我们访问，我们进行检测来查看我们是否正被请求退出。如果我们被请求退出，我们只是简单的设置time\_to\_exit，清除工作区的第一个字符，并且退出。

如果我们不希望退出，我们计算字符数然后清空第一个字符为空。我们使用将第一个字符清空的方法来通知读取程序我们已经完成了计算。我们然后解锁互斥量并且等待主线程运行。我们会循环尝试锁住这个互斥量，当我们成功时，我们会检测主线程是否为我们指定了更多的工作要做。如果没有，我们解锁互斥量并等待一段更长的时间。如果有，我们计算字符数并且再次进入循环。

下面是主线程：

pthread\_mutex\_lock(&work\_mutex);  
printf(“Input some text. Enter ‘end’ to finish\\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);  
sleep(1);  
}  
else {  
break;  
}  
}  
}  
pthread\_mutex\_unlock(&work\_mutex);

这与上面所说的线程类似。我们锁住工作区域，从而我们可以向其中读取文本，然后解锁允许其他的线程访问来计算单词数。循环往复，我们重新锁住互斥量，检测单词数是否进行了计算，如果我们需要等待更长的时间，我们就会释放这个锁。正如我们在前面所注意到的，这并不是一个好的编程习惯，而在真实的世界中，我们可以使用信号量来避免这种情况。然而，这里的代码只是作为一个例子。