并发:线程和锁
#include<stdio.h>
#include<pthread.h>
pthread_mutex_t lock;
//pthread_mutex_lock(&lock);
static volatile int counter = 0;
//pthread_mutex_unlock(&lock);
void* myLockThread(void* arg)
{
printf("%s: begin\n", (char*) arg);
int i;
//for (i=0; i<1e7;++i) ++counter;
for (i = 0; i < 1e8; ++i)
{
pthread_mutex_lock(&lock);
++counter;
pthread_mutex_unlock(&lock);
}
printf("%s: done\n", (char*) arg);
return NULL;
}
void* myThread(void* arg)
{
printf("%s: begin\n", (char*) arg);
int i;
for (i=0; i<1e8; ++i) ++counter;
printf("%s:done\n", (char*) arg);
return NULL;
}
int main(int argc, char* argv[])
{
pthread_t p1, p2;
printf("main: begin (counter = %d)\n", counter);
pthread_create(&p1, NULL, myLockThread, "A");
pthread_create(&p2, NULL, myLockThread, "B");
// join waits for the threads to finish
pthread_join(p1, NULL);
pthread_join(p2, NULL);
printf("main: done with both (counter = %d)\n", counter);
return 0;
}
time ./lock
main: begin (counter = 0)
A: begin
B: begin
A: done
B: done
main: done with both (counter = 200000000)
real 0m10.328s
user 0m13.250s
sys 0m6.297s
time ./a.out
main: begin (counter = 0)
A: begin
B: begin
B:done
A:done
main: done with both (counter = 116098548)
real 0m0.605s
user 0m1.172s
sys 0m0.000s
可见对让线程在临界区持有锁的做法,由于循环的存在,大幅度降低了性能,从而不如简单的同步实现