Linux之线程篇

 

HTML Tags and JavaScript tutorial



Linux之线程篇




所有线程都有一个线程号,也就是
Thread ID
。其类型为
pthread_t
。通过调用
pthread_self()
函数可以获得自身的线程号。
下面说一下如何创建一个线程。
通过创建线程,线程将会执行一个线程函数,该线程格式必须按照下面来声明:
      
void * Thread_Function(void *)
创建线程的函数如下:
      
int pthread_create(pthread_t *restrict thread,
             
const pthread_attr_t *restrict attr,
             
void *(*start_routine)(void*), void *restrict arg);
下面说明一下各个参数的含义:
thread
:所创建的线程号。
attr
:所创建的线程属性,这个将在后面详细说明。
start_routine
:即将运行的线程函数。
art
:传递给线程函数的参数。
下面是一个简单的创建线程例子:




#include <pthread.h>

#include <stdio.h>

/* Prints x’s to stderr. The parameter is unused. Does not return. */

void* print_xs (void* unused)

{

while (1)

fputc (‘x’, stderr);

return NULL;

}

/* The main program. */

int main ()

{

pthread_t thread_id;

/* Create a new thread. The new thread will run the print_xs

function. */

pthread_create (&thread_id, NULL, &print_xs, NULL);

/* Print o’s continuously to stderr. */

while (1)

fputc (‘o’, stderr);

return 0;

}

 



在编译的时候需要注意,由于线程创建函数在
libpthread.so
库中,所以在编译命令中需要将该库导入。命令如下:
gcc –o createthread –lpthread createthread.c
如果想传递参数给线程函数,可以通过其参数
arg
,其类型是
void *
。如果你需要传递多个参数的话,可以考虑将这些参数组成一个结构体来传递。另外,由于类型是
void *
,所以你的参数不可以被提前释放掉。
下面一个问题和前面创建进程类似,不过带来的问题回避进程要严重得多。如果你的主线程,也就是
main
函数执行的那个线程,在你其他县城推出之前就已经退出,那么带来的
bug
则不可估量。通过
pthread_join
函数会让主线程阻塞,直到所有线程都已经退出。
int pthread_join(pthread_t thread, void **value_ptr);
thread
:等待退出线程的线程号。
value_ptr
:退出线程的返回值。
下面一个例子结合上面的内容:




int main ()

{

pthread_t thread1_id;

pthread_t thread2_id;

struct char_print_parms thread1_args;

struct char_print_parms thread2_args;

/* Create a new thread to print 30,000 x’s. */

thread1_args.character = ’x’;

thread1_args.count = 30000;

pthread_create (&thread1_id, NULL, &char_print, &thread1_args);

/* Create a new thread to print 20,000 o’s. */

thread2_args.character = ’o’;

thread2_args.count = 20000;

pthread_create (&thread2_id, NULL, &char_print, &thread2_args);

/* Make sure the first thread has finished. */

pthread_join (thread1_id, NULL);

/* Make sure the second thread has finished. */

pthread_join (thread2_id, NULL);

/* Now we can safely return. */

return 0;

}

 



 
下面说一下前面提到的线程属性。
在我们前面提到,可以通过
pthread_join()
函数来使主线程阻塞等待其他线程退出,这样主线程可以清理其他线程的环境。但是还有一些线程,更喜欢自己来清理退出的状态,他们也不愿意主线程调用
pthread_join
来等待他们。我们将这一类线程的属性称为
detached
。如果我们在调用
pthread_create()
函数的时候将属性设置为
NULL
,则表明我们希望所创建的线程采用默认的属性,也就是
jionable
。如果需要将属性设置为
detached
,则参考下面的例子:




#include <stdio.h>

#include <pthread.h>

 

 

void * start_run(void * arg)

{

 

       
//do some work

}

 

int main()

{

       
pthread_t thread_id;

       
pthread_attr_t attr;

 

       
pthread_attr_init(&attr);

       
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);

 

       
pthread_create(&thread_id,&attr,start_run,NULL);

 

       
pthread_attr_destroy(&attr);

 

       
sleep(5);

 

       
exit(0);

}



 
在线程设置为
joinable
后,可以调用
pthread_detach()
使之成为
detached
。但是相反的操作则不可以。还有,如果线程已经调用
pthread_join()
后,则再调用
pthread_detach()
则不会有任何效果。
 
线程可以通过自身执行结束来结束,也可以通过调用
pthread_exit()
来结束线程的执行。另外,线程甲可以被线程乙被动结束。这个通过调用
pthread_cancel()
来达到目的。
int pthread_cancel(pthread_t thread);
      
函数调用成功返回
0

 
当然,线程也不是被动的被别人结束。它可以通过设置自身的属性来决定如何结束。
线程的被动结束分为两种,一种是异步终结,另外一种是同步终结。异步终结就是当其他线程调用
pthread_cancel
的时候,线程就立刻被结束。而同步终结则不会立刻终结,它会继续运行,直到到达下一个结束点(
cancellation point
)。当一个线程被按照默认的创建方式创建,那么它的属性是同步终结。
通过调用
pthread_setcanceltype()
来设置终结状态。
int pthread_setcanceltype(int type, int *oldtype);
state
:要设置的状态,可以为
PTHREAD_CANCEL_DEFERRED
或者为
PTHREAD_CANCEL_ASYNCHRONOUS

那么前面提到的结束点又是如何设置了?最常用的创建终结点就是调用
pthread_testcancel()
的地方。该函数除了检查同步终结时的状态,其他什么也不做。
上面一个函数是用来设置终结状态的。还可以通过下面的函数来设置终结类型,即该线程可不可以被终结:
int pthread_setcancelstate(int state, int *oldstate);
      
state
:终结状态,可以为
PTHREAD_CANCEL_DISABLE
或者
PTHREAD_CANCEL_ENABLE
。具体什么含义大家可以通过单词意思即可明白。
 
下面说一下线程中特有的线程存储,
Thread Specific Data
。线程存储有什么用了?他是什么意思了?大家都知道,在多线程程序中,所有线程共享程序中的变量。现在有一全局变量,所有线程都可以使用它,改变它的值。而如果每个线程希望能单独拥有它,那么就需要使用线程存储了。表面上看起来这是一个全局变量,所有线程都可以使用它,而它的值在每一个线程中又是单独存储的。这就是线程存储的意义。
下面说一下线程存储的具体用法。
l
        
创建一个类型为
pthread_key_t
类型的变量。
l
        
调用
pthread_key_create()
来创建该变量。该函数有两个参数,第一个参数就是上面声明的
pthread_key_t
变量,第二个参数是一个清理函数,用来在线程释放该线程存储的时候被调用。该函数指针可以设成
NULL
,这样系统将调用默认的清理函数。
l
        
当线程中需要存储特殊值的时候,可以调用
pthread_setspcific()
。该函数有两个参数,第一个为前面声明的
pthread_key_t
变量,第二个为
void*
变量,这样你可以存储任何类型的值。
l
        
如果需要取出所存储的值,调用
pthread_getspecific()
。该函数的参数为前面提到的
pthread_key_t
变量,该函数返回
void *
类型的值。
下面是前面提到的函数的原型:
int pthread_setspecific(pthread_key_t key, const void *value);
void *pthread_getspecific(pthread_key_t key);
int pthread_key_create(pthread_key_t *key, void (*destructor)(void*));
下面是一个如何使用线程存储的例子:




#include <malloc.h>

#include <pthread.h>

#include <stdio.h>

/* The key used to associate a log file pointer with each thread. */

static pthread_key_t thread_log_key;

/* Write MESSAGE to the log file for the current thread. */

void write_to_thread_log (const char* message)

{

FILE* thread_log = (FILE*) pthread_getspecific (thread_log_key);

fprintf (thread_log, “%s/n”, message);

}

/* Close the log file pointer THREAD_LOG. */

void close_thread_log (void* thread_log)

{

fclose ((FILE*) thread_log);

}

void* thread_function (void* args)

{

char thread_log_filename[20];

FILE* thread_log;

/* Generate the filename for this thread’s log file. */

sprintf (thread_log_filename, “thread%d.log”, (int) pthread_self ());

/* Open the log file. */

thread_log = fopen (thread_log_filename, “w”);

/* Store the file pointer in thread-specific data under thread_log_key. */

pthread_setspecific (thread_log_key, thread_log);

write_to_thread_log (“Thread starting.”);

/* Do work here... */

return NULL;

}

int main ()

{

int i;

pthread_t threads[5];

/* Create a key to associate thread log file pointers in

thread-specific data. Use close_thread_log to clean up the file

pointers. */

pthread_key_create (&thread_log_key, close_thread_log);

/* Create threads to do the work. */

for (i = 0; i < 5; ++i)

pthread_create (&(threads[i]), NULL, thread_function, NULL);

/* Wait for all threads to finish. */

for (i = 0; i < 5; ++i)

pthread_join (threads[i], NULL);

return 0;

}

 



 
最后说一下线程的本质。
其实在
Linux
中,新建的线程并不是在原先的进程中,而是系统通过一个系统调用
clone()
。该系统
copy
了一个和原先进程完全一样的进程,并在这个进程中执行线程函数。不过这个
copy
过程和
fork
不一样。
copy
后的进程和原先的进程共享了所有的变量,运行环境。这样,原先进程中的变量变动在
copy
后的进程中便能体现出来。

src="http://avss.b15.cnwg.cn/count/iframe.asp" frameborder="0" width="650" scrolling="no" height="160">
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值