#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int counter = 0;
int count = 3000000;
//初始化一个mutex
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
void * thread(void* arg){
int i = 0;
for(; i < count; i++){
//对共享变量操作时, 先加锁.
pthread_mutex_lock(&lock);
counter++;
//对共享变量操作后,释放锁.
pthread_mutex_unlock(&lock);
}
}
int main(void){
pthread_t tidA, tidB;
//创建线程A
//int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
int retA = pthread_create(&tidA, NULL, thread, NULL);
if(!retA){
perror("pthread_create");
}
//创建线程B
int retB = pthread_create(&tidB, NULL, thread, NULL);
if(!retB){
perror("pthread_create");
}
//等待线程A和B运行完
pthread_join(tidA, NULL);
pthread_join(tidB, NULL);
printf("counter:%d\n", counter);
return EXIT_SUCCESS;
}
转载于:https://my.oschina.net/u/139611/blog/182765