Linux多线程编程学习代码(代码已上传gitee,还请各位兄弟点个Star哦!)
https://gitee.com/chenshao777/linux_thread.git
笔记:
1.为了让线程访问数据不产生冲突,这要就需要对变量加锁,使得同一时刻只有一个线程可以访问变量。
2.互斥量本质就是锁,访问共享资源前对互斥量加锁,访问完成后解锁
3.当互斥量加锁以后,其他所有需要访问该互斥量的线程都将阻塞
4.当互斥量解锁以后,所有因为这个互斥量阻塞的线程都将变为就绪态,第一个获得cpu的线程会获得互斥量,变为运行态,
而其他线程会继续变为阻塞,在这种方式下访问互斥量每次只有一个线程能向前执行
5.互斥量用 pthread_mutex_t 类型的数据表示,在使用之前需要对互斥量初始化
1、如果是动态分配的互斥量,可以调用 pthread_mutex_init() 函数初始化
2、如果是静态分配的互斥量,还可以把它置为常量 PTHREAD_MUTEX_INITIALIZER
3、动态分配的互斥量在释放内存之前需要调用 pthread_mutex_destroy() 来销毁
int pthread_mutex_init(pthread_mutex_t *restrict mutex,
const pthread_mutexattr_t *restrict attr);
第一个参数是要初始化的互斥量,第二个参数是互斥量的属性﹐默认为NULL
int pthread_mutex_destroy(pthread_mutex_t *mutex);
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
spu.h文件
#ifndef _SPU_H_
#define _SPU_H_
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<signal.h>
#include<errno.h>
#endif
08.thread_mutex.c文件
/*
1.创建两个线程,都对 money 全局变量进行操作
2.线程1每次对 money 加10
3.线程2每次对 money 加0.01
4.如果出现互斥的情况,线程1会输出小数
*/
#include "spu.h"
//是否使用互斥量
#define mutex_flag 1
float money;
pthread_mutex_t mutex; //定义互斥量
void *thread_fun1(void *arg)
{
while(1)
{
#if mutex_flag
pthread_mutex_lock(&mutex); //上锁
#endif
money += 10;
printf("01: money = %.2f\n",money);
sleep(1);
#if mutex_flag
pthread_mutex_unlock(&mutex); //解锁
#endif
}
return (void*)1;
}
void *thread_fun2(void *arg)
{
while(1)
{
#if mutex_flag
pthread_mutex_lock(&mutex); //上锁
#endif
money += 0.01;
// printf("02: money = %.2f\n",money);
sleep(1);
#if mutex_flag
pthread_mutex_unlock(&mutex); //解锁
#endif
}
return (void*)2;
}
int main(int argc, char *argv[])
{
int err1, err2;
pthread_t thread_id1, thread_id2;
int s;
void *__retval;
//首先初始化互斥量,互斥量才可以使用
pthread_mutex_init(&mutex, NULL);
err1 = pthread_create(&thread_id1, NULL, thread_fun1, NULL);
if(err1 != 0)
printf("create thread01 failed!\n");
err2 = pthread_create(&thread_id2, NULL, thread_fun2, NULL);
if(err2 != 0)
printf("create thread02 failed!\n");
sleep(1);
pthread_exit(__retval);
}