不使用多线程同步,对全局整数进行++和打印操作:
//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
1894

被折叠的 条评论
为什么被折叠?



