作用
当多个线程访问其所共享的进程资源时,如果不相互协调,就会出现意料之外的错误。
例子
#include
#include
size_t cnt = 0;
void *thread_test(void *arg)
{
for(int i=0;i<10000000;i++)
cnt++;
return NULL;
}
int main()
{
pthread_t ids[2];
int i;
for(i=0;i<2;i++)
{
int ret = pthread_create(&ids[i],NULL,thread_test1,NULL);
if(ret)
{
printf("pthread_create() error!!!\n");
return -1;
}
}
for(i=0;i<2;i++)
{
int ret = pthread_join(ids[i],NULL);
if(ret)
{
printf("pthread_join() error!!!\n");
return -1;
}
}
printf("cnt : %d\n",cnt);
return 0;
}
以上结果,多次运行后,会发现cnt的值不一定为20000000.
互斥量
int pthread_mutex_init (pthread_mutex_t* mutex,const pthread_mutexattr_t* mutexattr);
int pthread_mutex_lock (pthread_mutex_t* mutex);
int pthread_mutex_unlock (pthread_mutex_t* mutex);
int pthread_mutex_destroy (pthread_mutex_t* mutex);
例子
#include
#include
size_t cnt = 0;
pthread_mutex_t mutex;
void *thread_test(void *arg)
{
for(int i=0;i<10000000;i++)
{
pthread_mutex_lock(&mutex);
cnt++;
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main()
{
pthread_t ids[2];
int i;
pthread_mutex_init(mutex,NULL);
for(i=0;i<2;i++)
{
int ret = pthread_create(&ids[i],NULL,thread_test1,NULL);
if(ret)
{
printf("pthread_create() error!!!\n");
return -1;
}
}
for(i=0;i<2;i++)
{
int ret = pthread_join(ids[i],NULL);
if(ret)
{
printf("pthread_join() error!!!\n");
return -1;
}
}
pthread_mutex_destroy(&mutex);
printf("cnt : %d\n",cnt);
return 0;
}
信号量
#include
int sem_init (sem_t* sem, int pshared,unsigned int value);
int sem_wait (sem_t* sem);
int sem_trywait (sem_t* sem);
int sem_timedwait (sem_t* sem,
const struct timespec* abs_timeout);
struct timespec {
time_t tv_sec;
long tv_nsec;
};
.int sem_post (sem_t* sem);
int sem_destroy (sem_t* sem);
例子
#include
#include
size_t cnt = 0;
sem_t sem;
void *thread_test(void *arg)
{
for(int i=0;i<10000000;i++)
{
sem_wait(&sem);
cnt++;
sem_post(&sem);
}
return NULL;
}
int main()
{
pthread_t ids[2];
int i;
sem_init(sem,0,1);
for(i=0;i<2;i++)
{
int ret = pthread_create(&ids[i],NULL,thread_test1,NULL);
if(ret)
{
printf("pthread_create() error!!!\n");
return -1;
}
}
for(i=0;i<2;i++)
{
int ret = pthread_join(ids[i],NULL);
if(ret)
{
printf("pthread_join() error!!!\n");
return -1;
}
}
sem_destroy(&sem);
printf("cnt : %d\n",cnt);
return 0;
}
条件变量
需要与互斥锁配合使用,代码参考消费者生产者模型。
int pthread_cond_init (pthread_cond_t* cond,const pthread_condattr_t* attr);
int pthread_cond_wait (pthread_cond_t* cond,pthread_mutex_t* mutex);
int pthread_cond_timedwait (pthread_cond_t* cond,pthread_mutex_t* mutex,const struct timespec* abstime);
int pthread_cond_signal (pthread_cond_t* cond);
int pthread_cond_broadcast (pthread_cond_t* cond);
int pthread_cond_destroy (pthread_cond_t* cond);