线程私有数据

参考

Posix线程编程指南(2)

范例的代码其实意义不大,child2函数完全没有必要。作者没有解释对于struct等复杂类型该如何做的问题,也就是为什么会有echomsg的问题。

1.echomsg 其实是个注册的destructor,永远释放在线程中分配的私有数据,由于pthread_setspecific(key,(void *)tid);只能对指针进行操作,所以malloc之类的操作必不可少。

2.对于struct的读写,需要分配一个struct类型的变量。
具体的代码如下。
#include <stdio.h>
#include
<stdlib.h>
#include
<pthread.h>
#include
<unistd.h>
struct thread_block
{
pthread_t tid;
long start;
long end;
};


pthread_key_t key;
void
freeblock (
struct thread_block *pt)
{
printf (
"thread %lu\t start %lu \t end %lu\n", pt->tid, pt->start, pt->end);
free (pt);
}

void *
child1 (
void *arg)
{
int tid = pthread_self ();
printf (
"thread %d enter\n", tid);
struct thread_block *pt =
(
struct thread_block *) malloc (sizeof (struct
thread_block));
pt
->tid = tid;
pt
->start = *(int *) arg;
pt
->end = pt->start + 1000;

pthread_setspecific (key, (
void *) pt);
sleep (
2);
printf (
"thread %d\n", tid);
sleep (
5);
}

int
main (
void)
{
int tid1, tid2;
int start = 100;
printf (
"hello\n");
pthread_key_create (
&key, freeblock);
pthread_create (
&tid1, NULL, child1, &start );

start
+= 1000;
pthread_create (
&tid2, NULL, child1, &start);
sleep (
10);
pthread_key_delete (key);
printf (
"main thread exit\n");
return 0;
}

  请注意黑线表示的语句是变化的了的。


原文地址:https://www.cnblogs.com/westfly/p/2169863.html