UNIX环境高级编程学习之第十二章线程控制-以分离状态创建线程
[code lang=”cpp”]/*
FileName: CreateDetachThread.c
Date: 20100624
Desc: gcc CreateDetachThread.c -lpthread -o demo
以分离状态创建线程
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <signal.h>

pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER; // 互斥锁定义并初始化
pthread_cond_t g_cond = PTHREAD_COND_INITIALIZER; // 条件变量定义并初始化

struct msg { // 链表
struct msg *m_next;
char data[100]; // 处理数据
};
struct msg * msgHead = NULL;

void* thread_fun(void * arg)
{
struct msg *msgCur; // 当前数据
while (1)
{
pthread_mutex_lock(&g_mutex);
while(msgHead == NULL)
pthread_cond_wait(&g_cond, &g_mutex);
msgCur = msgHead;
msgHead = msgHead->m_next;
/* 处理数据 msgCur */
printf("Data:%s/n", msgCur->data);
free(msgCur);
msgCur = NULL;
pthread_mutex_unlock(&g_mutex);
}
return (void*)1;
}

int main(int argc, char* argv[])
{
int ret;
pthread_t t;
pthread_attr_t attr; // 线程属性
ret = pthread_attr_init(&attr); // 初始化线程属性
if (ret != 0)
{
printf(" pthread_attr_init() is Error t1 /n");
exit(-1);
}
ret = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); // 设置线程属性为分离状态
if (ret != 0)
{
printf(" pthread_attr_setdetachstate() is Error t1 /n");
exit(-1);
}
ret = pthread_create(&t, &attr, thread_fun, NULL); // 创建线程加入线程属性
if (ret != 0)
{
printf("pthread_create() is Error t1 /n");
exit(-1);
}
ret = pthread_attr_destroy(&attr); // 销毁线程属性内的空间
/* 每隔两秒添加一次数据 */
struct msg *msgCur;
while (1)
{
pthread_mutex_lock(&g_mutex);
msgCur = malloc(sizeof(struct msg));
if (msgCur == NULL)
{
printf("malloc() is Failed! /n");
exit(-1);
}
memset(msgCur, 0x00, sizeof(struct msg));
msgCur->m_next = msgHead;
strcpy(msgCur->data, "Hello");
msgHead = msgCur;
pthread_mutex_unlock(&g_mutex);
pthread_cond_signal(&g_cond);
sleep(2);
}
pthread_mutex_destroy(&g_mutex); // 销毁互斥锁
pthread_cond_destroy(&g_cond); // 销毁条件
return 0;
}

[/code]

发表评论