实验17
1
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
pid_t pid;
char*msg;
int k;
printf("观察父子进程执行的先后顺序,了解调度算法的特征\n");
pid=fork();
switch(pid) {
case 0:
msg="子进程在运行";
k=3;
break;
case -1:
msg="进程创建失败";
break;
default:
msg="父进程在运行";
k=5;
break;
}
while(k>0)
{
puts(msg);
sleep(1);
k--; }
exit(0);
}
2
并发程序-父子进程线程异步性
#include <stdio.h>
#include <pthread.h>
static int run=1;
static int retvalue;
void *threadfunc(void*arg) {
int*running=arg;
printf("子线程初始化完毕,传入参数为:
%d\n",*running);
while(*running)
{
printf("子线程正在运行\n");
usleep(1);
}
printf("子线程退出\n");
retvalue=8;
pthread_exit((void*)&retvalue);
}
int main()
{
pthread_t pt;
int ret=-1;
int times=3;
int i=0;
int *ret_join=NULL;
ret=pthread_create(&pt,NULL,(void*)threadfun
c,&run);
if(ret!=0)
{
printf("建立线程失败\n");
return 1;
}
printf("主线程创建子线程后在运行...\n");
usleep(1);
printf("主线程调用usleep(1)...\n");
for(;i<times;i++)
{
printf("主线程打印i=%d\n",i);
usleep(1);
}
run=0;
pthread_join(pt,(void*)&ret_join);
printf("线程返回值为:%d\n",*ret_join);
return 0;
}
编译: gcc thread.c -o thread -lpthread 运行: ./thread
3
多线程对共享变量的非互斥访问
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
int num=30,count=10;
void *sub1(void *arg) {
int i = 0,tmp;
for (; i <count; i++)
{
tmp=num-1;
usleep(13);
num=tmp;
printf("线程1 num减1后值为: %d\n",num);
}
return ((void *)0);
}
void *sub2(void *arg){
int i=0,tmp;
for(;i<count;i++)
{
tmp=num-1;
usleep(31);
num=tmp;
printf("线程2 num减1后值为: %d\n",num);
}
return ((void *)0);
}
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);
}
for(;i<count;i++)
{
tmp=num-1;
usleep(5);
num=tmp;
printf("main num减1后值为: %d\n",num);
}
printf("两个线程运行结束\n");
err=pthread_join(tid1,&tret);
if(err!=0)
{
printf("can not join with
thread1:%s\n",strerror(err));
exit(-1);
}
printf("thread 1 exit code %d\n",(int)tret);
err=pthread_join(tid2,&tret);
if(err!=0)
{
printf("can not join with
thread1:%s\n",strerror(err));
exit(-1);
}
printf("thread 2 exit code %d\n",(int)tret);
return 0;
}
|