学习笔记:
学习内容:
线程常用基本函数:
- pthread_create() 创建线程
- pthread_exit() 退出当前线程
- pthread_join() 等待其他线程结束
- pthread_self() 自身线程ID号
- pthread_cancel() 停止其他线程
- pthread_detach() 分离某个线程
学习笔记:
线程使用需要导入对应头文件
pthread_create() 创建线程
函数原型:
int pthread_create(pthread_t *th,
const pthread_attr_t *attr,
void *(* func)(void *),
void *arg);
pthread_exit() 退出当前线程
函数原型:
void pthread_exit(void *res);
pthread_join() 等待其他线程结束
函数原型:
int pthread_join(pthread_t th, void **res);
pthread_self() 自身线程ID号
函数原型:
pthread_t pthread_self(void);
pthread_cancel() 停止其他线程
函数原型:
int pthread_cancel(pthread_t th);
pthread_detach() 分离某个线程
函数原型:
int pthread_detach(pthread_t th);
示例程序:
demo:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#include <pthread.h>
#define OPEN_DEBUG_MESSAGE
#ifdef OPEN_DEBUG_MESSAGE
# define D_MES(message) printf(message)
#else
# define D_MES(message)
#endif
typedef struct TResultTag TRes;
struct TResultTag
{
char data[20];
int num;
};
void *task1_entry(void *param)
{
TRes *res = (TRes *)param;
int i;
for(i = 0; i < 10; i++)
{
printf("task i -> %d\n",i);
sleep(1);
}
sprintf(res->data, "task1 id:%lu", pthread_self());
res->num = 520;
pthread_exit(param);
}
int main()
{
printf("hello\n");
TRes *res = (TRes *)malloc(sizeof(TRes));
if (res != NULL)
{
pthread_t task1;
if (pthread_create(&task1, NULL, task1_entry, res) != 0)
printf("failed in pthread_create \n");
sleep(1);
int i;
for(i = 0; i < 5; i++)
{
printf("main i -> %d\n",i);
sleep(1);
}
if (pthread_join(task1, (void **)&res) == 0)
printf("res->data:%s\nres->:%d\n", res->data, res->num);
else
printf("ERROR: pthread_join");
}
else
printf("failed in malloc\n");
system("pause");
return 0;
}
效果截图
-
不执行pthread_detach()
-
执行pthread_detach()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)