1、单线程的锁用局部锁,锁不住其他线程的访问
#include <stdio.h>
#include <pthread.h>
typedef struct {
int num;
char array[20];
} PthreadTestPara_t;
PthreadTestPara_t p_struct[20] = {0};
int g_num = 0;
void *PthreadGetDataFromArray(void *argv)
{
PthreadTestPara_t *p = (PthreadTestPara_t *)argv;
pthread_mutex_t lock;//改成全局变量就不一样了
pthread_mutex_lock(&lock);
printf("pthread[%x] : num : %d\n", (unsigned int)pthread_self(), p->num);
g_num = p->num;
printf("pthread[%x] : g_num : %d\n", (unsigned int)pthread_self(), g_num);
sleep(3 * p->num);
pthread_mutex_unlock(&lock);
}
int main()
{
pthread_t pid;
int i = 0;
for (i = 0; i < 5; i++) {
p_struct[i].num = i;
pthread_create(&pid, NULL, PthreadGetDataFromArray, (void *)&(p_struct[i]));
pthread_detach(pid);
}
sleep(50);
return 0;
}
最终结果如下:
pthread[b6592b40] : num : 2
pthread[b6592b40] : g_num : 2
pthread[b6d93b40] : num : 1
pthread[b6d93b40] : g_num : 1
pthread[b5d91b40] : num : 3
pthread[b5d91b40] : g_num : 3
pthread[b5590b40] : num : 4
pthread[b5590b40] : g_num : 4
说明该锁没有作用。其他线程还是可以访问的,将该锁改成全局的,用的是一把锁,效果就如下:
pthread[b75d0b40] : num : 0
pthread[b75d0b40] : g_num : 0
pthread[b6dcfb40] : num : 1
pthread[b6dcfb40] : g_num : 1
pthread[b65ceb40] : num : 2
pthread[b65ceb40] : g_num : 2
pthread[b5dcdb40] : num : 3
pthread[b5dcdb40] : g_num : 3
pthread[b55ccb40] : num : 4
pthread[b55ccb40] : g_num : 4
临界资源的访问,锁的加入是为了确定谁用使用权。 照上面的测试结果,谁对临界资源的使用权判断,是靠一把锁来确定的,而且始终是这把锁。