进程与线程
操作系统以进程为单位,为每个进程分配执行所需要的资源。各个进程相互独立,原则上各进程之间不允许访问对方的资源。同一时间,操作系统可以运行多个进程,每个进程可以同时执行多个任务。
线程是操作系统能够进行调度的最小单位,是进程的实际运行单位。一个进程可以并发多个线程,每条线程并行执行不同的任务。
线程的操作
多线程开发在Linux平台上有pthread库支持。线程操作有线程创建、等待和退出三种操作。
头文件:#include<pthread.h>
命令编译时加 -lpthread
线程创建
int pthread_create(
pthread_t *restrict thread, //线程id
const pthread_attr_t *restrict attr, //线程属性,默认可置为NULL,表示线程属性取缺省值
void *(*start_routine)(void*), //线程入口函数
void *restrict arg //线程入口函数的参数
);
线程创建成功时,返回非0值,成功则返回0.
线程等待
int pthread_join(pthread_t thread, void **rval_ptr);
以阻塞的方式令主线程等待thread指定的线程结束。如果没有该函数,主线程的执行速度很快,有可能发生主线程执行结束子线程还没有创建成功。
示例1
文件名:pthread.c
运行命令:
gcc pthread.c -o pthread -lpthread
#include <stdio.h>
#include <pthread.h>
void thread()
{
printf("This is the new pthread.\n");
}
int main(int argc, const char *argv[])
{
int ret = 0;
pthread_t id;
ret = pthread_create(&id, NULL, (void *) thread, NULL);
if(ret)
{
printf("Create pthread error!\n");
return 1;
}
printf("this is main process.\n");
pthread_join(i,NULL);
return 0;
}
示例2
打印进程输出的时间
程序内容:创建两个子进程,每个进程延时1s循环输出。
#include <stdio.h>
#include <pthread.h>
#include<unisted>
#include<time.h>
void *mythread1(void)
{
int i;
for(i = 0; i < 3; i++)
{
printf("This is the 1st pthread.\n");
time_t currentTm = time(NULL);
puts(asctime(localtime(¤tTm)));
sleep(1);
}
}
void *mythread2(void)
{
int i;
for(i = 0; i < 10; i++)
{
printf("This is the 2st pthread.");
time_t currentTm = time(NULL);
puts(asctime(localtime(¤tTm)));
sleep(1);
}
}
int main(int argc, const char *argv[])
{
int i = 0;
int ret = 0;
pthread_t id1,id2;
ret = pthread_create(&id1, NULL, (void *)mythread1,NULL);
if(ret)
{
printf("Create pthread error!\n");
return 1;
}
ret = pthread_create(&id2, NULL, (void *)mythread2,NULL);
if(ret)
{
printf("Create pthread error!\n");
return 1;
}
pthread_join(id1,NULL);
pthread_join(id2,NULL);
return 0;
}
运行结果:三秒时间分别输出进程1和进程2的打印语句。
程序内容:创建两个进程,进程1延时循环打印,进程2不延时打印。
#include <stdio.h>
#include <pthread.h>
#include<unisted>
#include<time.h>
void *mythread1(void)
{
int i;
for(i = 0; i < 3; i++)
{
printf("This is the 1st pthread.\n");
time_t currentTm = time(NULL);
puts(asctime(localtime(¤tTm)));
sleep(1);
}
}
void *mythread2(void)
{
int i;
for(i = 0; i < 10; i++)
{
printf("This is the 2st pthread.");
time_t currentTm = time(NULL);
puts(asctime(localtime(¤tTm)));
}
}
int main(int argc, const char *argv[])
{
int i = 0;
int ret = 0;
pthread_t id1,id2;
ret = pthread_create(&id1, NULL, (void *)mythread1,NULL);
if(ret)
{
printf("Create pthread error!\n");
return 1;
}
ret = pthread_create(&id2, NULL, (void *)mythread2,NULL);
if(ret)
{
printf("Create pthread error!\n");
return 1;
}
pthread_join(id1,NULL);
pthread_join(id2,NULL);
return 0;
}
运行结果:进程1第一次的打印和进程2的三次打印同时实行,之后分别显示进程1的后两次打印。