前言
本章主要介绍线程的使用。
一、pthread
#include <pthread.h>
pthread_t pthread_self(void);//获取自身的线程ID
int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(start_rtn)(void *), void *restrict arg);//创建线程
void pthread_exit(void *rval_ptr);//终止线程
int pthread_join(pthread_t thread,void **rval_ptr);//调用线程一致阻塞,直到指定的线程调用pthread_exit退出,rval_ptr返回错误码。
二、例程
1.pthread线程创建退出回收
代码如下(示例):
void *thr_fn1(void *arg)
{
printf("thread 1 returning\n");
return ((void*)1);
}
void *thr_fn2(void *arg)
{
printf("thread 2 returning\n");
return ((void*)2);
}
void unix_11_3_pthread(void)
{
int err;
pthread_t tid1,tid2;
void *tret;
err = pthread_create(&tid1,NULL,thr_fn1,NULL);
if(err != 0)
err_exit(err,"can't create thread 1");
err = pthread_create(&tid2,NULL,thr_fn2,NULL);
if(err != 0)
err_exit(err,"can't create thread 2");
err = pthread_join(tid1,&tret);
if(err != 0)
err_exit(err,"can't join with thread 1");
printf("thread 1 exit code %ld\n",(long)tret);
err = pthread_join(tid2,&tret);
if(err != 0)
err_exit(err,"can't join with thread 2");
printf("thread 2 exit code %ld\n",(long)tret);
exit(0);
}
#define UNIX_11_3_PTHREAD
int main(int argc, char *argv[])
{
#ifdef UNIX_11_3_PTHREAD
unix_11_3_pthread();
#endif
printf("MAIN END\n");
return 0;
}
结果:
2.主线程和新创建线程比较
代码如下(示例):
pthread_t ntid;
void printids(const char *s)
{
pid_t pid;
pthread_t tid;
pid = getpid();
tid = pthread_self();
printf("%s pid %lu tid %lu (0x%lx)\n",s,(unsigned long)pid,(unsigned long)tid,(unsigned long)tid);
}
void *thr_fn(void *arg)
{
printids("new thread: ");
return ((void*)0);
}
void unix_11_2_pthread(void)
{
int err;
err = pthread_create(&ntid,NULL,thr_fn,NULL);
if(err != 0)
err_exit(err,"can't create thread");
printids("main thread:");
sleep(1);
exit(0);
}
#define UNIX_11_2_PTHREAD
int main(int argc, char *argv[])
{
#ifdef UNIX_11_2_PTHREAD
unix_11_2_pthread();
#endif
printf("MAIN END\n");
return 0;
}
结果
总结
本章主要简单介绍了创建线程及其例程。