Linux下C语言多线程编程实例(用C语言模拟word软件,一边输入,一边统计字符)

25 篇文章 22 订阅
下面通过两个实例来讲解多线程编程。
1.首先先举一个简单的多线程程序吧,让大家好理解多线程编程。

代码如下:

<span style="font-size:14px;">#include<pthread.h>
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
void *mythread(void *arg)
{
	int v=*(int *)arg;
	printf("v= %d\n",v);

	while(1)
	{
		printf("my thread\n");
		sleep(2);
	}
}

int main(int argc,char* argv[])
{
	int i=5;
	pthread_t tid;

	pthread_create(&tid,NULL,mythread,&i);
	
	while(1)
	{
		printf("main thread\n");
		sleep(1);
	}

	return 0;
}
</span>
编译:在终端中输入:gcc test.c -lpthread。
运行:在终端中输入:./a.ou
效果如下:



2.下面写一个动态统计字数的程序。

程序功能:模拟word软件,用户可以从键盘输入字符,敲下回车,程序动态的统计字符个数。

程序代码如下:

<span style="font-size:14px;">#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<string.h>
char text[4096]={0};
int flag=0;

void *mythread(void *arg)
{
	int v=*(int *)arg;

	while(1)
	{
		if(flag==1)
		{
			printf("current length of text is : %d\n ",strlen(text));
			flag=0;
		}
		usleep(10000);
	}
}
int main(int argc,char* argv[])
{
	int i=5;
	pthread_t tid;
	char buf[128];

	pthread_create(&tid,NULL,mythread,&i);
	
	while(1)
	{
		memset(buf,0,sizeof(buf));
		gets(buf);
		strcat(text,buf);
		flag=1;		
	}

	return 0;
}

//gcc test.c -lpthread
</span>

编译运行方法同上。
下面给出运行截图:


注:博主使用的是Ubuntu12.4操作系统,程序都通过了编译执行。

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值