Linux多线程编程
Linux多线程设计是指基于Linux操作系统下的多线程设计,包括多任务程序的设计,并发程序设计,网络程序设计,数据共享等。
Linux系统下的多线程遵循POSX线程接口,称为pthread
(1)使用函数创建。
返回值:成功-0,失败-返回错误编号,可以用strerror(errno)函数得到错误信息。
(2)使用pthread_join函数等待指定线程结束
int pthread_join(pthread_t thread,void**value_ptr);
参数:
一个有效的线程id;接收线程返回值的指针;
*注:调用此函数的线程在指定的线程退出前将处于挂起状态或出现错误而直接返回,如果value_ptr非NULL则value_ptr指向线程返回值的指针,函数成功后指定的线程使用的资源将被释放
(3)线程的终止:三种方式
1)线程从启动例程中返回,返回值是线程的退出码;
2)线程调用了pthead_exit函数;这里不是调用exit,因为线程调用exit函数,会导致线程所在的进程退出。
3)线程可以被同一进程中的其他线程取消。
关于编译线程程序的方式,例如源程序为xxx.c
编译方式是gcc xxx.c -o xxx -lpthread
调试方式:./xxx
练习1:编写包含一个主线程和三个子线程的多线程并发程序。
代码实现如下
#include<pthread.h>
#include<stdio.h>
void *printyou(void *unused)//pthread1
{
int c=2000;
while(c--) fputs("you",stderr);
return NULL;
}
void *printme(void *unused)//pthread2
{
int c=2000;
while(c--) fputs("me",stderr);//stderr标准输出(设备)文件,对应终端的屏幕。
//进程将从标准输入文件中得到输入数据,将正常输出数据输出到标准输出文件,而将错误信息送到标准错误文件中
return NULL;
}
void *printthem(void *unused)//pthread3
{
int c=2000;
while(c--) fputs("them",stderr);
return NULL;
}
int main(int argc, char *argv[])//main
{
int c=2000;
pthread_t tid1,tid2,tid3;//pthread_t线程标识符
pthread_create(&tid1,NULL,&printyou,NULL);//pthread_create创建线程
pthread_create(&tid2,NULL,&printme,NULL);
pthread_create(&tid3,NULL,&printthem,NULL);
while(c--) fputs('o',stderr);
printf("\n");
return 0;
}
练习2:贵阳到广州的高铁G200还剩200张票,甲乙两家旅行社都可以购买了该趟车的车票,在8:00-12:00期间两家旅行社分别购买了60张票,余票为200-60*2=80。编写程序模拟该售票过程。
代码实现
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<unistd.h>
#include<string.h>
int num=200,count=60;
pthread_mutex_t myLock=PTHREAD_MUTEX_INITIALIZER;//静态初始化互斥锁
void *sub1(void *arg){//company 1 buy tickects
int i,tmp;
for(i=1;i<=count;i++){
pthread_mutex_lock(&myLock);
printf("thread1:before buying,tickets num=%d\n",num);
tmp=num-1;
printf("thread1:during ordering,ticket num=%d\n",tmp);
num=tmp;
printf("thread1:after buying,ticket num=%d\n",num);
pthread_mutex_unlock(&myLock);
}
return "Tread ended...";
}
void *sub2(void *arg){//company2 buy tickects
int i,tmp;
for(i=1;i<=count;i++){
pthread_mutex_lock(&myLock);
printf("thread2:before buying,tickets num=%d\n",num);
tmp=num-1;
printf("thread2:during ordering,ticket num=%d\n",tmp);
num=tmp;
printf("thread2:after buying,ticket num=%d\n",num);
pthread_mutex_unlock(&myLock);
}
return "Tread ended...";
}
int main(int argc,char *argv[]){
pthread_t tid1,tid2;
int err,i=0,tmp;
void *tret;
err=pthread_create(&tid1,NULL,sub1,NULL);
if(err!=0)
{
printf("pthread create error:%s\n",strerror(err));
exit(-1);
}
err=pthread_create(&tid2,NULL,sub2,NULL);
if(err!=0)
{
printf("pthread create error:%s\n",strerror(err));
exit(-1);
}
printf("buying finined!\n");
err=pthread_join(tid1,&tret);//block thread which it's id is tid1
if(err!=0)
{
printf("can not join with thread1:%s\n",strerror(err));
exit(-1);
}
printf("thread1 exit %s\n",(char *)tret);
err=pthread_join(tid2,&tret);//block thread which it's id is tid2
if(err!=0)
{
printf("can not join with thread2:%s\n",strerror(err));
exit(-1);
}
printf("thread2 exit %s\n",(char *)tret);
return 0;
}
执行结果如图
练习三:编写多线程代码使输出类似于下图结果
代码如下
#include <pthread.h>
#include <stdio.h>
#include <sys/time.h>
#include <string.h>
#include<unistd.h>
#define MAX 10
pthread_t thread[2];
pthread_mutex_t mut;
int number=0,i;
void *thread1()
{
printf("thread:I'm thread 1/n");
for(i=0;i<MAX;i++)
{
printf("thread1:number=%d/n",number);
pthread_mutex_lock(&mut);
number++;
pthread_mutex_unlock(&mut);
sleep(2);
}
printf("thread1:main thread is waiting for me?/n");
pthread_exit(NULL);
}
void *thread2()
{
printf("thread:I'm thread 2/n");
for(i=0;i<MAX;i++)
{
printf("thread2:number=%d/n",number);
pthread_mutex_lock(&mut);
number++;
pthread_mutex_unlock(&mut);
sleep(3);
}
printf("thread2:main thread is waiting for me?/n");
pthread_exit(NULL);
}
void thread_create(void)
{
int temp;
memset(&thread,0,sizeof(thread));//comment1
/*创建线程*/
if((temp=pthread_create(&thread,NULL,thread1,NULL))!=0) //comment2
printf("thread1 is createdfailed!/n");
else
printf("thread1 is created!/n");
if((temp=pthread_create(&thread,NULL,thread2,NULL))!=0) //comment3
printf("thread2 is createdfailed!/n");
else
printf("thread2 is created!/n");
}
void thread_wait(void)
{
/*等待线程结束*/
if(thread[0]!=0)
{
pthread_join(thread[0],NULL);
printf("thread1 is finished/n");
} //comment4
if(thread[1]!=0)
{
pthread_join(thread[1],NULL);
printf("thread2 is finished/n");
} //comment5
}
int main()
{
/*用默认属性初始化互斥锁*/
pthread_mutex_init(&mut,NULL);
printf("I am main thread,I am create thread!/n");
thread_create();
printf("I am main thread,I am waiting for thread finishing!/n");
thread_wait();
return 0;
}
代码执行结果
(第一个代码没放执行结果因为在我的电脑上跑出现了段错误,暂时没找到解决方法)
//第一个题的代码出现的段错误如图
代码在windows下跑没问题,在Linux下出现了警告如图
原因:fputs函数的第一个参数一个是字符串,我给了字符型,所以编译出现类型不匹配,然后给的生成的数据类型长度过小,所以溢出。
(语法没问题,语义有错误!!C语言还有很多探索之处呢!!)
改正:while(c–) fputs(‘o’,stderr);改成while(c–) fputs(“o”,stderr);
正确运行结果