线程定义:
线程,有时被称为轻量级进程(Lightweight Process,LWP),是程序执行流的最小单元。另外,线程是进程中的一个实体,是被系统独立调度和分派的基本单位,线程自己不拥有系统资源,只拥有一点儿在运行中必不可少的资源,但它可与同属一个进程的其它线程共享进程所拥有的全部资源。一个线程可以创建和撤消另一个线程,同一进程中的多个线程之间可以并发执行。线程是程序中一个单一的顺序控制流程。进程内一个相对独立的、可调度的执行单元,是系统独立调度和分派CPU的基本单位指运行中的程序的调度单位。
多线程是什么呢?
在单个程序中同时运行多个线程完成不同的工作,称为多线程。
我们用一个例子来体会一下会更深刻。
/* 1_pthread.c*/
#include <stdio.h>
#include <pthread.h>
/*线程一*/
void thread1(void)
{
int i=0;
for(i=0;i<6;i++){
printf("This is a pthread1.\n");
if(i==2)
pthread_exit(0);
sleep(1);
}
}
/*线程二*/
void thread2(void)
{
int i;
for(i=0;i<3;i++)
printf("This is a pthread2.\n");
pthread_exit(0);
}
int main(void)
{
pthread_t id1,id2;
int i,ret;
/*创建线程一*/
ret=pthread_create(&id1,NULL,(void *) thread1,NULL);
if(ret!=0){
perror("Create pthread error!\n");
}
/*创建线程二*/
ret=pthread_create(&id2,NULL,(void *) thread2,NULL);
if(ret!=0){
perror ("Create pthread error!\n");
}
/*等待线程结束*/
pthread_join(id1,NULL);
pthread_join(id2,NULL);
return 0;
}
在终端测试一下:
ubuntu:~/test/pthread_test$ gcc 1_pthread.c -o 1_pthread -lpthread
ubuntu:~/test/pthread_test$ ./1_pthread
This is a pthread1.
This is a pthread2.
This is a pthread2.
This is a pthread2.
This is a pthread1.
This is a pthread1.
再执行一次:
ubuntu:~/test/pthread_test$ ./1_pthread
This is a pthread2.
This is a pthread2.
This is a pthread2.
This is a pthread1.
This is a pthread1.
This is a pthread1.
从上面的示例程序可以看出,两个线程是并发运行。线程执行时,并不能保证哪个线程先执行,这是线程的一大特点。想要控制顺序,也是有方法的,需要用到同步相关知识,后续慢慢道来。
从上面的例子中,我们发现想要读懂程序,需要了解几个函数:pthread_create、pthread_exit、pthread_join
下面来看看这几个函数:
创建线程函数pthread_create:
#include <pthread.h>
int pthread_create ((pthread_t *thread, pthread_attr_t *attr,
void *(*start_routine)(void *), void *arg))
返回值:成功:0;出错:-1
函数参数:
- thread:线程标识符
- attr:线程属性设置
- start_routine:线程函数的起始地址
- arg:传递给 start_routine 的参数
退出线程函数pthread_exit:
#include <pthread.h>
void pthread_exit(void *retval)
函数参数:
- Retval:保存的是线程退出以后返回的值,可由其他函数如 pthread_join 来检索获取。
如果在线程中使用exit()函数退出,那么整个的进程将会退出。我们可以使用pthread_exit来只退出当前线程。
线程挂起函数pthread_join:
#include <pthread.h>
int pthread_join ((pthread_t th, void **thread_return))
返回值:若成功,返回0;若失败,返回-1
函数参数:
- th:等待线程的标识符
- thread_return:用户定义的指针,用来存储被等待线程的返回值(不为 NULL 时)
pthread_join 可以用于将当前线程挂起,等待线程的结束。这个函数是一个线程阻塞的函数,调用它的函数将一直等待到被等待的线程结束为止,当函数返回时,被等待线程的资源就被收回。
从以上知识,我们对线程就有了基本的认识。接下来有时间再写一篇线程同步的一些机制。