现在的位置: 首页 > 综合 > 正文

Linux 多线程编程(Pthread 库)学习笔记 二

2013年09月02日 ⁄ 综合 ⁄ 共 2231字 ⁄ 字号 评论关闭

 

线程数据处理 之 线程数据

 

为了保护变量,我们必须使用信号量、互斥等方法来保证我们对变量的正确使用。

1) 线程数据
在单线程的程序里,有两种基本的数据:全局变量和局部变量。但在多线程程序里,还有第三种数据类型:线程数据(TSD: Thread-Specific Data)。它和全局变量很象,在线程内部,各个函数可以象使用全局变量一样调用它,但它对线程外部的其它线程是不可见的.

线程存储的具体用法

创建一个类型为 pthread_key_t 类型的变量。

           调用 pthread_key_create() 来创建该变量。该函数有两个参数,第一个参数就是上面声明的 pthread_key_t 变量,第二个参数是一个清理函数,用来在线程释放该线程存储的时候被调用。该函数指针可以设成 NULL ,这样系统将调用默认的清理函数。

 

当线程中需要存储特殊值的时候,可以调用 pthread_setspcific() 。该函数有两个参数,第一个为前面声明的 pthread_key_t 变量,第二个为 void* 变量,这样你可以存储任何类型的值。

如果需要取出所存储的值,调用 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;

}  

 

 

抱歉!评论已关闭.