一 基本概念:
線程是進程執行的最基本單位,是一個正在運行的函數,通常包括:main線程與兄弟線程。線程間通信共享進程虛擬內存空間。
常用的線程標識:
pthread_t
常用api:
比較線程pid:
int pthread_equal(pthread_t t1, pthread_t t2);
返回線程標識:
pthread_t pthread_self(void);
二 線程常見狀態與操作:
1 線程創建
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg);
其中:線程回填標識、線程屬性(常見NULL),線程執行函數入口地址、函數的參數。成功返回0,失敗返回錯誤碼。
2 線程的終止
1)線程從啓動例程返回,返回值是線程的退出碼
2)線程可以被同一個進程中的其他線程取消
3)線程調用void pthread_exit(void *value_ptr);
棧的清理 防止線程意外退出,掛上回調函數,等到棧清理時執行內容
void pthread_cleanup_push(void (*cleanup_routine)(void *), void *arg);
void pthread_cleanup_pop(int execute);
3 線程的取消
先取消後收屍
int pthread_cancel(pthread_t thread);
取消包括:允許與不允許
允許取消又分爲:異步cancel、推遲cancel(默認)
cancel點:posix定義的cancel點都是可以引發阻塞的系統調用
int pthread_setcancelstate(int state, int *oldstate);是否允許取消
int pthread_setcanceltype(int type, int *oldtype);設置取消方式
int pthread_detach(pthread_t thread);線程分離,已經分離的線程不允許收屍
操作實例:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<pthread.h>
/*
1 線程創建與調度
*/
void * func1(void *p)
{
puts("thread is working!");
pthread_exit(NULL);
}
void test1()
{
pthread_t tid;
int err;
puts("start!");
err = pthread_create(&tid,NULL,func1,NULL);
if(err)
{
fprintf(stderr, "pthread_create():%s\n", strerror(err));
exit(-1);
}
puts("end!");
pthread_join(tid, NULL);
}
/*
2 線程棧的清理
*/
void cleanup_func(void *p)
{
puts(p);
}
void * func2(void *p)
{
puts("thread is working!");
pthread_cleanup_push(cleanup_func, "cleanup1");
pthread_cleanup_push(cleanup_func, "cleanup2");
pthread_cleanup_push(cleanup_func, "cleanup3");
pthread_cleanup_pop(1);
pthread_cleanup_pop(1);
pthread_cleanup_pop(1);
pthread_exit(NULL);
}
void test2()
{
pthread_t tid;
int err;
puts("start!");
err = pthread_create(&tid,NULL,func2,NULL);
if(err)
{
fprintf(stderr, "pthread_create():%s\n", strerror(err));
exit(-1);
}
puts("end!");
pthread_join(tid, NULL);
}
int main()
{
test2();
exit(0);
}