今天得知了参加的最后一场暑期实习生的招聘结果,我又被刷了,沮丧了几天之后,有人告诉我那家公司不招c/c++方向的,还有半个月就放暑假了,是继续看书学习,还是去实践,很迷茫,真的感觉时间不够用。
这篇用来记录线程,几个星期之前,我看过这篇,当时理解记忆了,可是今天回过头来再看,感觉还是记不清楚,可能是没有系统的总结吧。这篇就总结一下:
#include <pthread.h>
int pthread_equal(pthread_t t1, pthread_t t2);
pthread_t pthread_self(void);
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
Compile and link with -pthread.(第一次线程程序时总是出错,后来看文档发现有这句话,所以文档永远是最好的书籍)上面的三个函数,我个人觉得第三个当然时最重要的,重点解读一下:
pthread_t *thread:存储创建的新线程的ID
const pthread_attr_t *attr:定制线程属性
void *(*start_routine) (void *):函数指针,新线程从start_routine开始运行
void *arg:如果需要向上面的函数传递多个参数,可以采用结构体,把地址作为arg参数传入
程序如下:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void print(const char*s)
{
pid_t pid;
pthread_t tid;
pid=getpid();
tid=pthread_self();
printf("%s pid %u tid %u (0x%x)\n",s,(unsigned int)pid, (unsigned int)
tid,(unsigned int)tid);
}
void *thr_fn(void *args)
{
print("new thread:");
return ((void*)0);
}
int main()
{
pthread_t ntid;
int err;
err=pthread_create(&ntid, NULL,thr_fn,NULL);
print("main_thread:");
sleep(1);
exit(0);
}
我们先记住线程可以在不终止整个进程的情况下通过以下方式退出:
(1)只是从启动例程返回,返回值时退出码,如:return
(2)调用pthread_exit,和第一条类似
(3)被同一进程的其他线程取消
下面看另外三个函数:
#include <pthread.h>
void pthread_exit(void *retval)
int pthread_join(pthread_t thread, void **retval)
int pthread_cancel(pthread_t thread)
第一个函数返回退出码,第二个函数取出特定线程的退出码,线程没退出,该函数将一直阻塞
程序如下:
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
void *thr_fn1()
{
printf("thread1 is returning\n");
return ((void*)1);
}
void *thr_fn2()
{
printf("thread2 is exiting\n");
pthread_exit ((void*)2);
}
void main()
{
int err;
pthread_t tid1, tid2;
void *tret;
err=pthread_create(&tid1, NULL, thr_fn1,NULL);
if(err != 0)
printf("create thread1 error\n");
err=pthread_create(&tid2, NULL, thr_fn2,NULL);
if(err != 0)
printf("create thread2 error\n");
err=pthread_join(tid1, &tret);
if(err != 0)
printf("can't join thread1\n");
printf("thread 1 exit code %d\n",(int)tret);
err=pthread_join(tid2, &tret);
if(err != 0)
printf("can't join thread2\n");
printf("thread 2 exit code %d\n",(int)tret);
exit(0);
}
至于pthread_cancel取决于cancelability state and type.
在我们进一步学习线程同步前,一定要记住这些函数(@_@)