在学习多线程程序设计之前,先要了解下多进程与多线程之间的一个比较:
与多进程相比较而言,多线程比较“节俭”:
(1):启动一个进程,必须得给它分配独立的地址空间,需要建立更多的数据来维护它的代码段、堆栈段与数据段。
但是线程却不需要,同一个进程下的线程是共享数据段的。
(2):线程之间的彼此切换时间所需要的时间也远远小于进程间切换所需要的时间。
1:Linux下的Pthread
Linux系统下的多线程遵循POSIX线程接口,称之为Pthread
编写Linux下的多线程程序,需要: 头文件:Pthread.h 需要的库:libpthread.a |
1)创建线程——pthread_create
#include <pthread.h>
int pthread_create(pthread_t *restrict thread,const pthread_attr_t *restruct attr,void *(*start_routine) (void *),void *restruct arg);
参数说明:
thread:指向线程标识符的指针
attr:用来设置线程属性,不必设置属性时设置为NULL;
start_routine:线程运行时函数的起始地址
arg:运行函数的参数
实例:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h> //静态链接库,编译时加上-lpthread
struct menber{
int a;
char *s;
};
void *create(void *arg)
{
struct menber *temp;
temp=(struct menber *)arg;
printf("menber->a = %d \n",temp->a);
printf("menber->s = %s \n",temp->s);
return (void *)0;
}
int main()
{
pthread_t tidp;
int error;
struct menber *b;
b=(struct menber*)malloc(sizeof(struct menber));
b->a=4;
b->s="zieckey";
error = pthread_create(&tidp,NULL,create,(void*)b);//创建线程并运行线程执行函数
if(error)
{
printf("pthread is not create...\n");
return -1;
}
sleep(1);//进程睡眠1秒,使线程执行完后进程才会结束
printf("pthread is created...\n");
return 0;
}