linux多线程【1】demo

不使用多线程同步,对全局整数进行++和打印操作:

//thread.c
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <pthread.h>
void *func(void *);
int g_a=0;
pthread_mutex_t t1;
int main()
{
	pthread_t pt1,pt2;
	pthread_mutex_init(&t1,NULL);
	pthread_create(&pt1,NULL,func,NULL);
	pthread_create(&pt2,NULL,func,NULL);

	pthread_join(pt1,NULL);
	pthread_join(pt2,NULL);
        pthread_mutex_destroy(&t1);
        return 0;
}

void *func(void*d)
{
	
	//pthread_mutex_lock(&t1);
	int i=0;
	while(i<100)
	{
		g_a++;
		printf("g_a = %d\n", g_a);
		i++;
	}
	//pthread_mutex_unlock(&t1);
	return NULL;
}


应该是200才对。

去掉注释:

void *func(void*d)
{
	
	pthread_mutex_lock(&t1);
	int i=0;
	while(i<100)
	{
		g_a++;
		printf("g_a = %d\n", g_a);
		i++;
	}
	pthread_mutex_unlock(&t1);
	return NULL;
}

执行结果:

或者使用pthread_mutex_trylock:

void *func(void*d)
{
	
	while(pthread_mutex_trylock(&t1)!=0)
	{
		printf("EBUSY\n");
	}
	int i=0;
	while(i<100)
	{
		g_a++;
		printf("g_a = %d\n", g_a);
		i++;
	}
	pthread_mutex_unlock(&t1);
	return NULL;
}




注意,编译时要使用-lpthread选项,该选项要放在.c文件之后。

administrator@ubuntu:~/test$ gcc thread.c -lpthread -o thread


ref:

http://code.google.com/p/ldd6410/wiki/LinuxThread




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值