“资源”的竞争。
(因为多线程是同时运行的,而我们往往不会去控制线程运行的顺序,不然也不会用多线程了),导致可一些我们不愿见到的结果,所以我们每个线程对全局变量的操作都希望是原子性的。
#include
intsem_init(sem_t *sem, int pshared, unsigned int value);
sem:就是信号量的标识符
pshared:0, 表示该信号量用于线程之间的通信。
0, 表示该信号量用于进程程之间的通信。
value:非负的整数,就是信号量的初值。
0, 表示没有资源。
intsem_wait(sem_t *sem);
0时,睡眠等待。
1.
sem:
intsem_trywait(sem_t *sem);
intsem_post(sem_t *sem);
1.
intsem_getvalue(sem_t *sem, int *svalue);
sem, 指定要获得的信号量
svalue,用于保存获得的信号量的值。
intsem_destroy(sem_t *sem);
intpthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t*restrict attr);
mutex: 线程锁的标识符
attr:设置线程锁的属性,通常为NULL。
pthread_mutex_tlock;
pthread_mutex_init(&lock,NULL);
intpthread_mutex_lock(pthread_mutex_t *mutex);
intpthread_mutex_unlock(pthread_mutex_t *mutex);
:解锁。
intpthread_mutex_destroy(pthread_mutex_t *mutex);
intpthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrictattr);
cond: 条件变量的标识符
atrr:条件变量的属性,通常为NULL。
pthread_cond_tcond;
pthread_cond_init(&cond,NULL);
intpthread_cond_signal(pthread_cond_t *cond);
intpthread_cond_broadcast(pthread_cond_t *cond);
intpthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrictmutex);
cond :需要改条件变量
mutex:就是一个锁。
pthread_cond_wait():先将锁解开,然后进入睡眠,当被唤醒的时候需要重新加锁(如果此时得不到锁,那么继续睡眠)。
intpthread_cond_destroy(pthread_cond_t *cond);
“顺利执行”,执行完毕后再通知其他线程执行。而互斥锁是典型的互斥机制,对资源加以保护,在这期间不允许其他现场对保护的内容进行读写操作。通过信号量和条件变量都可以实现经典的生产者消费者模式。