// To-Do
// 实现一个线程安全的方法
// 功能与ThreadFunc一致,实现global_value += 1
// 要求:通过互斥锁来实现,pthread_mutex
1.代码用到的关于互斥锁的知识点
第一步:先定义变量。pthread_mutex_t mutex;
第二步:初始化锁。pthread_mutex_init(&mutex,NULL);
第三步:将需要上锁的代码或者函数部分进行上锁。pthread_mutex_lock(&mutex);
第四步:解锁。pthread_mutex_unlock(&mutex);
第五步:摧毁互斥锁pthread_mutex_destroy(&mutex);
2.关于线程用到的知识点
第一步声明变量 pthread_t ntid;
第二步pthread_create(&ntid, NULL, thr_fn, ¶m1); //ntid是线程的变量名,第二个参数是线程属性一般为NULL,thr_fn 是线程应该运行的程序,第四个参数是函数的参数。如果结果返回为0,则是成功创建线程。
第三步用 int pthread_join(pthread_t thread, void ** retval); thread是线程变量名,retval是线程返回值,放到里面。它的目的是堵塞主线程。
例如:res = pthread_join(myThread, &thread_result);
res=pthread_join(myThread,NULL);
#include<stdlib.h>
#include<string.h>
#include <unistd.h>
#include <pthread.h>
static int pthread_num = 10; /*线程总数*/
int global_value = 0;
pthread_mutex_t mutex;
void *ThreadFunc(void *arg){//dayinzhengzaiyunxingdexiancheng
int v = global_value;
printf("the %dth thread is running, which thread_id is %lu, and current value is %d \n", *(int *)arg, pthread_self(), v);
global_value = v + 1;
}
void *LockedThreadFunc(void *arg){
// To-Do
// 实现一个线程安全的方法
// 功能与ThreadFunc一致,实现global_value += 1
// 要求:通过互斥锁来实现,pthread_mutex
//
pthread_mutex_lock(&mutex);
int v=global_value;
printf("the %dth thread is running , which thread_id is %lu, and current value is %d \n",*(int *)arg, pthread_self(),v);
global_value=v+1;
pthread_mutex_unlock(&mutex);
}
int main(int argc, char const *argv[]){
/* code */
pthread_mutex_init(&mutex,NULL);
int i = 0;
int *inc = 0;
void * t_result;
pthread_t tid[10];
while(i < pthread_num){
// if ((pthread_create(&tid[i], NULL,ThreadFunc, (void *)&i)) == -1){
if ((pthread_create(&tid[i], NULL, LockedThreadFunc, (void *)&i)) == -1){
printf("create thread error!\n");
}
i++;
}
for(i=0;i < pthread_num;i++){
pthread_join(tid[i],NULL);
}
printf("the global value is %d at last.",global_value);
pthread_mutex_destroy(&mutex);
}