一、实现方式
各线程之间栈区独享、并且与进程共享文本段、数据段、堆区,所以可以通过全局变量实现多线程间通信。
int num = 0; //创建一个全局变量void *thread1(void *arg)
{while (1){num = 100; //线程一中给全局变量num赋值100}return NULL;
}void *thread2(void *arg)
{while (1){printf("num = %d\n",num);
//由于多个线程之间共享进程的全局变量,所以当线程一运行后,线程二打印的结果num = 100;
//但由于线程之间宏观并行,运行的先后顺序不确定,所以会存在线程二先与运行的情况,当线程二先运行,这里打印结果是num = 0 }return NULL;
}int main(int argc, const char **argv)
{pthread_t tid1;pthread_t tid2;pthread_create(&tid1, NULL, thread1, NULL);pthread_create(&tid2, NULL, thread2, NULL);pthread_join(tid1, NULL);pthread_join(tid2, NULL);return 0;
}
线程1先执行,线程2后执行的打印情况(线程间的通讯)
二、锁
1、互斥锁
(1)概念
为了防止多线程操作全局变量带来的资源竞争,需要引入互斥锁的概念
(2)互斥锁函数接口
man 3 pthread_mutex_init
int pthread_mutex_init(pthread_mutex_t *restrict mutex,
const pthread_mutexattr_t *restrict attr);
功能:
互斥锁的初始化,锁的初始化得放在线程创建之前
参数:
mutex:互斥锁的首地址,pthread_nutex_t lock;(得是全局变量),所有线程共用一把锁
attr:属性,默认为NULL
返回值:
成功返回0
失败返回错误码
man 3 pthread_mutex_lock
int pthread_mutex_lock(pthread_mutex_t *mutex);
功能:
加锁
int pthread_mutex_unlock(pthread_mutex_t *mutex);
功能:
解锁
int pthread_mutex_destroy(pthread_mutex_t *mutex);
功能:
销毁互斥锁 ,锁的销毁得放在线程回收之后
两个都不锁
int num = 0;void *thread1(void *arg)
{while (1){num = 100;}return NULL;
}void *thread2(void *arg)
{while (1){num = 200;printf("%d\n",num);//线程之间宏观并行,微观串行;所以线程在执行的过程中,会出现以下情况://情况一:线程1先执行,线程二后执行//情况二:线程2先执行,线程1后执行//情况三:线程2执行一半后执行线程1,线程1执行一半后执行线程2,即二者交叉执行//所以这里的打印结果是不确定的}return NULL;
}int main(int argc, const char **argv)
{pthread_t tid1;pthread_t tid2;pthread_create(&tid1, NULL, thread1, NULL);pthread_create(&tid2, NULL, thread2, NULL);pthread_join(tid1, NULL);pthread_join(tid2, NULL);return 0;
}
打印结果:
锁一个
int num = 0;
pthread_mutex_t lock;void *thread1(void *arg)
{while (1){num = 100;}return NULL;
}void *thread2(void *arg)
{while (1){//锁一个不行,另一个没锁住还是会干扰到被锁住的线程的执行,两个都锁住才能避免冲突//当两个都锁住后,一个执行完毕不代表另一个会一定接着执行,有可能还会执行第二遍刚执行完毕的线程pthread_mutex_lock(&lock);num = 200;printf("num = %d\n", num);pthread_mutex_unlock(&lock);}return NULL;
}int main(int argc, const char **argv)
{pthread_t tid1;pthread_t tid2;pthread_mutex_init(&lock, NULL);pthread_create(&tid1, NULL, thread1, NULL);pthread_create(&tid2, NULL, thread2, NULL);pthread_join(tid1, NULL);pthread_join(tid2, NULL);pthread_mutex_destroy(&lock);return 0;
}
打印结果:
锁两个
int num = 0;
pthread_mutex_t lock;void *thread1(void *arg)
{while (1){pthread_mutex_lock(&lock);num = 100;pthread_mutex_unlock(&lock);}return NULL;
}void *thread2(void *arg)
{while (1){pthread_mutex_lock(&lock);num = 200;printf("num = %d\n", num);pthread_mutex_unlock(&lock);}return NULL;
}int main(int argc, const char **argv)
{pthread_t tid1;pthread_t tid2;pthread_mutex_init(&lock, NULL);pthread_create(&tid1, NULL, thread1, NULL);pthread_create(&tid2, NULL, thread2, NULL);pthread_join(tid1, NULL);pthread_join(tid2, NULL);pthread_mutex_destroy(&lock);return 0;}
执行结果