1.同步
同一个进程中的多个线程共享所在进程的内存资源,当多个线程在同一时刻同时访问同一种共享资源时,需要相互协调,以避免出现数据的不一致和覆盖等问题,线程之间的协调和通信的就叫做线程的同步问题, 线程同步的思路: 让多个线程依次访问共享资源,而不是并行
我们可以使用信号量进行同步。如:thread2等待thread1发送信号量,才能执行printf语句。#include
#include
#include
sem_t sem1, sem2;
void *thread1(void *arg) {
for (int i = 0; i < 3; ++i) {
sem_post(&sem2);
}
}
void *thread2(void *arg) {
while(1) {
sem_wait(&sem2);
printf("world!\n");
}
}
int main() {
pthread_t t1, t2;
sem_init(&sem1,0,1);
sem_init(&sem2,0,0);
pthread_create(&t1,NULL,thread1,NULL);
pthread_create(&t2,NULL,thread2,NULL);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
sem_destroy(&sem1);
sem_destroy(&sem2);
return 0;
}
extern int sem_init __P ((sem_t *__sem, int __pshared, unsigned int __value));
sem为指向信号量结构的一个指针;pshared不为0时此信号量在进程间共享,否则只能为当前进程的所有线程共享;value给出了信号量的初始值。
函数sem_post( sem_t *sem )用来增加信号量的值。当有线程阻塞在这个信号量上时,调用这个函数会使其中的一个线程不在阻塞,选择机制同样是由线程的调度策略决定的。
函数sem_wait( sem_t *sem )被用来阻塞当前线程直到信号量sem的值大于0,解除阻塞后将sem的值减一,表明公共资源经使用后减少。函数sem_trywait ( sem_t *sem )是函数sem_wait()的非阻塞版本,它直接将信号量sem的值减一。函数sem_destroy(sem_t *sem)用来释放信号量sem。
信号量用sem_init函数创建的,下面是它的说明: int sem_init (sem_t *sem, int pshared, unsigned int value);
这个函数的作用是对由sem指定的信号量进行初始化,设置好它的共享选项,并指定一个整数类型的初始值。pshared参数控制着信号量的类型。如果 pshared的值是0,就表示它是当前里程的局部信号量;否则,其它进程就能够共享这个信号量。我们现在只对不让进程共享的信号量感兴趣。 (这个参数受版本影响), pshared传递一个非零将会使函数调用失败。
这两个函数控制着信号量的值,它们的定义如下所示:
#include
int sem_wait(sem_t * sem);
int sem_post(sem_t * sem);
这两个函数都要用一个由sem_init调用初始化的信号量对象的指针做参数。
#include
#include
#include
pthread_mutex_t Device_mutex ;
int count=0;
void *thread_func1(void *args)
{
while(1)
{
pthread_mutex_lock(&Device_mutex);
printf("thread1: %d\n", count);
pthread_mutex_unlock(&Device_mutex);
count++;
sleep(1);
}
}
void *thread_func2(void *args)
{
while(1)
{
pthread_mutex_lock(&Device_mutex);
printf("thread2: %d\n", count);
pthread_mutex_unlock(&Device_mutex);
count++;
sleep(1);
}
}
int main() {
int a;
pthread_t thread1, thread2;
pthread_mutex_init(&Device_mutex, NULL);
pthread_create(&thread1, NULL, thread_func1, &a);
pthread_create(&thread2, NULL, thread_func2, &a);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
pthread_mutex_destroy(&Device_mutex);
return 0;
}
#include
pthread_t mutex //定义互斥锁
pthread_mutex_init() //初始化锁
pthread_mutex_lock()/pthread_mutex_trylock() ... //加锁
pthread_mutex_unlock() //解锁
pthread_mutex_destroy() //销毁
//成功返回0,失败返回error number
#include
int pthread_mutex_init (pthread_mutex_t *mutex, const pthread_mutexattr_t *mutexattr);
int pthread_mutex_lock (pthread_mutex_t *mutex);
int pthread_mutex_trylock (pthread_mutex_t *mutex);
int pthread_mutex_unlock (pthread_mutex_t *mutex);
int pthread_mutex_destroy (pthread_mutex_t *mutex);