---
title: "POSIX线程－（六）"
author: "winzenghua"
date: "2009-07-23T18:24:00Z"
tags: []
slug: "posix"
draft: false
lastmod: "2009-07-23T18:24:00Z"
id: 948813
url: "https://java4gis.iteye.com/blog/948813"
---

**线程属性－调度**

下面我们来看一下我们也许希望改变的第二个线程属性：调度。改变调度属性与设置分离属性相类似，但是我们可以使用另外两个函数来查找可用的等级级别，sched\_get\_priority\_max与sched\_get\_priority\_min。

**试验－－调度**

因为thread6.c是与前面的例子十分类似，这里我们只看一下其中的区别。

1 首先，我们需要一些额外的变量：

int max\_priority;  
int min\_priority;  
struct sched\_param scheduling\_value;

2 在我们设置分离属性之后，我们设置调度策略。

res = pthread\_attr\_setschedpolicy(&thread\_attr, SCHED\_OTHER);  
if (res != 0) {  
perror("Setting scheduling policy failed");  
exit(EXIT\_FAILURE);  
}

3 接下来我们查看允许级别的范围：

max\_priority = sched\_get\_priority\_max(SCHED\_OTHER);  
min\_priority = sched\_get\_priority\_min(SCHED\_OTHER);

4 并且设置一个级别：

scheduling\_value.sched\_priority = min\_priority;  
res = pthread\_attr\_setschedparam(&thread\_attr, &scheduling\_value);  
if (res != 0) {  
perror("Setting scheduling priority failed");  
exit(EXIT\_FAILURE);  
}

**工作原理**

这个例子与设置分离状态属性相类似，所不同的是我们设置调度策略。

**关闭线程**

有时我们希望一个线程可以请求另一个线程结束，而不是向其发送一个信号。线程有一个方法可以完成这个任务，而且并行使用信号处理，线程具有一个在他们被请求结束时修改其行为的方法。

首先我们来看一下请求线程结束的函数：

#include &lt;pthread.h&gt;  
int pthread\_cancel(pthread\_t thread);

这个函数声明很显示：给定一个线程标识符，我们可以请求其关闭。在收到关闭请求之后，事情有一些复杂，但是并不是很多。一个线程可以使用pthread\_setcancelstate来设置其关闭状态。

#include &lt;pthread.h&gt;  
int pthread\_setcancelstate(int state, int \*oldstate);

第一个参数或者为PTHREAD\_CANCEL\_ENABLE，这个参数允许线程接收关闭请求，或者是PTHREAD\_CANCEL\_DISABLE，这个参数会使得函数忽略关闭请求。oldstate指针允许获取前一个状态。如果我们对这个状态不感兴趣，我们可以简单的传递一个NULL。如果接受了关闭请求，线程可以采用一个第二级控制，关闭类型，这是由pthread\_setcanceltype来设置的。

#include &lt;pthread.h&gt;  
int pthread\_setcanceltype(int type, int \*oldtype);

这个类型的值可以为PTHREAD\_CANCEL\_ASYNCHRONOUS，这个类型可以在接收到关闭请求后立即执行，或者为PTHREAD\_CANCEL\_DEFERRED，这个类型会使得关闭请求等待直到执行下列函数中的一个：pthread\_join，pthread\_cond\_wait，pthread\_cond\_timedwait，pthread\_testcancel，sem\_wait或者是sigwait。

在这一章我们并没有看到这些函数，因为并不是所有的函数都需要。如以前的一样，更为详细的信息可以在手册中查看。

再一次说明，oldtype允许获取前一个状态，如果我们对前一个状态不感兴趣，我们可以传递一个NULL。默认情况下，线程以关闭状态PTHREAD\_CANCEL\_ENABLE与关闭状态PTHREAD\_CANCEL\_DEFERRED开始。

**试验－－关闭线程**

我们这里的程序thread7.c是由thread1.c发展来的。这一次，主线程向其所创建的线程发送一个关闭请求。

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

void \*thread\_function(void \*arg);

int main()  
{  
int res;  
pthread\_t a\_thread;  
void \*thread\_result;

res = pthread\_create(&a\_thread,NULL,thread\_function,NULL);  
if(res != 0)  
{  
perror("Thread creation failed");  
exit(EXIT\_FAILURE);  
}  
sleep(3);  
printf("Canceling thread...\\n");  
res = pthread\_cancel(a\_thread);  
if(res != 0)  
{  
perror("Thread cancelation failed");  
exit(EXIT\_FAILURE);  
}  
printf("Waiting for thread to finish...\\n");  
res = pthread\_join(a\_thread,&thread\_result);  
if(res != 0)  
{  
perror("Thread join failed");  
exit(EXIT\_FAILURE);  
}  
exit(EXIT\_SUCCESS);  
}

void \*thread\_function(void \*arg)  
{  
int i, res;  
res = pthread\_setcancelstate(PTHREAD\_CANCEL\_ENABLE,NULL);  
if(res != 0)  
{  
perror("Thread pthread\_setcancelstate failed");  
exit(EXIT\_FAILURE);  
}  
res = pthread\_setcanceltype(PTHREAD\_CANCEL\_DEFERRED,NULL);  
if(res != 0)  
{  
perror("Thread pthread\_setcanceltype failed");  
exit(EXIT\_FAILURE);  
}  
printf("Thread\_function is running\\n");  
for(i=0;i&lt;10;i++)  
{  
printf("Thread is still running (%d)...\\n",i);  
sleep(1);  
}  
pthread\_exit(0);  
}

**工作原理**

在用通常的方法创建一个新线程之后，主线程休眠（允许新线程启动）并且发送一个关闭请求。

sleep(3);  
printf("Canceling thread...\\n");  
res = pthread\_cancel(a\_thread);  
if(res != 0)  
{  
perror("Thread cancelation failed");  
exit(EXIT\_FAILURE);  
}

在所创建的线程中，我们首先设置关闭状态允许关闭。

res = pthread\_setcancelstate(PTHREAD\_CANCEL\_ENABLE,NULL);  
if(res != 0)  
{  
perror("Thread pthread\_setcancelstate failed");  
exit(EXIT\_FAILURE);  
}

然后我们设置关闭类型。

res = pthread\_setcanceltype(PTHREAD\_CANCEL\_DEFERRED,NULL);  
if(res != 0)  
{  
perror("Thread pthread\_setcanceltype failed");  
exit(EXIT\_FAILURE);  
}

最后线程等待关闭。

for(i=0;i&lt;10;i++)  
{  
printf("Thread is still running (%d)...\\n",i);  
sleep(1);  
}

**多线程**

直到现在，我们总是使得程序的一个执行线程只创建一个线程。然而，我们不希望使得大家认为我们只能创建一个线程。

试验－－多线程

作为我们本章的最后一个例子，thread8.c，我们演示如何在同一个程序中创建多个线程，并且以他们启动的不同顺序来收集这些线程。

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

#define NUM\_THREADS 6

void \*thread\_function(void \*arg);

int main()  
{  
int res;  
pthread\_t a\_thread\[NUM\_THREADS];  
void \*thread\_result;  
int lots\_of\_threads;

for(lots\_of\_threads = 0;lots\_of\_threads &lt; NUM\_THREADS; lots\_of\_threads++)  
{  
res = pthread\_create(&(a\_thread\[lots\_of\_threads]),NULL,thread\_function,(void \*)&lots\_of\_threads);  
if(res != 0)  
{  
perror("Thread creation failed");  
exit(EXIT\_FAILURE);  
}  
sleep(1);  
}  
printf("Waiting for threads to finish...\\n");  
for(lots\_of\_threads = NUM\_THREADS -1;lots\_of\_threads &gt;=0;lots\_of\_threads--)  
{  
res = pthread\_join(a\_thread\[lots\_of\_threads],&thread\_result);  
if(res == 0)  
{  
printf("Picked up a thread\\n");  
}  
else  
{  
perror("pthread\_join failed");  
}  
}  
printf("All done\\n");  
exit(EXIT\_SUCCESS);  
}

void \*thread\_function(void \*arg)  
{  
int my\_number = \*(int \*)arg;  
int rand\_num;

printf("thread\_function is running. Argument was %d\\n",my\_number);  
rand\_num = 1+(int)(9.0\*rand()/(RAND\_MAX+1.0));  
sleep(rand\_num);  
printf("Bye from %d\\n",my\_number);  
pthread\_exit(NULL);  
}

当我们运行这个程序时，我们会得到下面的输出：

$ ./thread8  
thread\_function is running. Argument  
thread\_function is running. Argument  
thread\_function is running. Argument  
thread\_function is running. Argument  
thread\_function is running. Argument  
Bye from 1  
thread\_function is running. Argument  
Waiting for threads to finish...  
Bye from 5  
Picked up a thread  
Bye from 0  
Bye from 2  
Bye from 3  
Bye from 4  
Picked up a thread  
Picked up a thread  
Picked up a thread  
Picked up a thread  
Picked up a thread  
All done

正如我们所看到的，我们创建了多个线程，并且允许他们以乱序结束 。在这个程序中存在一个bug，如果我们由启动线程的循环中移除sleep调用就会得到验证。我们包含就要演示当我们使用线程编写程序时需要小心。可以定位吗？我们会在下面的"工作原理"部分进行解释。

**工作原理**

这一次我们创建一个线程ID数组：

pthread\_t a\_thread\[NUM\_THREADS];

并且循环来创建多个线程：

for(lots\_of\_threads = 0; lots\_of\_threads &lt; NUM\_THREADS; lots\_of\_threads++) {  
res = pthread\_create(&(a\_thread\[lots\_of\_threads]), NULL,  
thread\_function, (void \*)&lots\_of\_threads);  
if (res != 0) {  
perror("Thread creation failed");  
exit(EXIT\_FAILURE);  
}  
sleep(1);  
}

这些线程在退出之前等待一个随机时间：

void \*thread\_function(void \*arg) {  
int my\_number = \*(int \*)arg;  
int rand\_num;  
printf("thread\_function is running. Argument was %d\\n", my\_number);  
rand\_num=1+(int)(9.0\*rand()/(RAND\_MAX+1.0));  
sleep(rand\_num);  
printf("Bye from %d\\n", my\_number);  
pthread\_exit(NULL);  
}

而在主线程中，我们等待收集这些线程，但是并不是以他们被创建的顺序。

for(lots\_of\_threads = NUM\_THREADS - 1; lots\_of\_threads &gt;= 0; lots\_of\_threads—)  
{  
res = pthread\_join(a\_thread\[lots\_of\_threads], &thread\_result);  
if (res == 0) {  
printf("Picked up a thread\\n");  
}  
else {  
perror("pthread\_join failed");  
}  
}

如果我们运行没有sleep调用的程序，我们就会看到一些奇怪的作用，包括一些线程使用相同的参数启动。我们是否定位这些情况了呢？线程正在使用一个局部变量作为线程函数的参数进行启动。这个变量是在循环中进行更新的。这个更新发生在下面的代码行中：

for(lots\_of\_threads = 0; lots\_of\_threads &lt; NUM\_THREADS; lots\_of\_threads++) {  
res = pthread\_create(&(a\_thread\[lots\_of\_threads]), NULL,  
thread\_function, (void \*)&lots\_of\_threads);

如果主线程运行得足够快，他就会为某些线程修改这个参数。类似的行为在使用共享变量与多执行路径时没有引起足够的注意造成的。我们已经警告过大家线程需要小心的设计。要修改这个问题，我们需要像如下的样子来直接传递这个值：

res = pthread\_create(&(a\_thread\[lots\_of\_threads]), NULL, thread\_function, (void  
\*)lots\_of\_threads);

并且修改thread\_function：

void \*thread\_function(void \*arg) {  
int my\_number = (int)arg;

**小结**

在这一章，我们了解了如何在一个进程内部创建多个执行线程，而其中每个线程共享文件域变量。然后我们探讨了线程控制对临界代码与数据的访问方法，使用信号量与互斥。在此之后，我们讨论了线程属性的控制，而且讨论了我们如何将他们与主线程分离，从而他不再等待他所创建的线程结束。在快速了解了线程如何请求另一个线程完成与接收线程如何管理这些请求之后，我们提供了一个多个并行线程执行的例子。

我们并没有足够的空间来讨论每一个函数调用与相关的线程，但是我们现在应具有足够的知识来使用线程编写我们的程序，并且可以通过阅读手册页来探讨更多的线程知识。