记录一些c多线程编程代码

代码来源与b站的一个up主 https://www.bilibili.com/video/av39377772/?p=4

#include 
#include 
#include 

/*
* 初始化5000个随机数,然后用两个线程求和
*/

typedef struct{
	int first;     //开始指针
	int last;	   //结束指针
	int result;    //保存结果
} MY_ARGS;

int arr[5000];
int s1=0;
int s2=0;

void* myfunc(void* args){
	int i;
	int s=0;
	MY_ARGS *my_args=(MY_ARGS*)args;    //将参数转换成结构体的类型
	int first = my_args->first;
	int last = my_args->last;
	for(i=first; iresult = s;
	return NULL;
}

int main(){
	int i;
	for(i=0; i<5000; i++){
		arr[i] = rand() % 50;            //初始化5000个随机数
	}
	pthread_t th1;
	pthread_t th2;

	MY_ARGS args1 = {0, 2500, 0};
	MY_ARGS args2 = {2500, 5000, 0};

	pthread_create(&th1, NULL, myfunc, &args1);
	pthread_create(&th2, NULL, myfunc, &args2);
	
	pthread_join(th1, NULL);
	pthread_join(th2, NULL);
	
	int s1 = args1.result;
	int s2 = args2.result;
	printf("s1=%d\n", s1);
	printf("s2=%d\n", s2);
	printf("s1+s2=%d\n", s1+s2);
	return 0;
}
#include 
#include 
#include 

/*
*这个程序展示mutex锁的用法
*/
int s=0;
pthread_mutex_t lock;

void* myfunc(void* args){
	int i=0;
	for(i=0; i<100000; i++){
		pthread_mutex_lock(&lock);
		s++;
		pthread_mutex_unlock(&lock);
	}
	return NULL;
}

int main(){
	pthread_t th1;
	pthread_t th2;
	
	pthread_mutex_init(&lock, NULL);
	
	pthread_create(&th1, NULL, myfunc, NULL);
	pthread_create(&th2, NULL, myfunc, NULL);
	
	pthread_join(th1, NULL);
	pthread_join(th2, NULL);
	
	printf("s=%d", s);
	return 0;
}
#include 
#include 
#include 
#define MAX_SIZE 5000
/*
* 这个程序介绍的是假共享 False sharing
* 如果把结果数组变成全局变量,
* 那么会比把结果写在各个线程里更慢一点
*/

typedef struct{
	int first;
	int last;
	int id;
}MY_ARGS;

int* arr;
int results[2];

void* myfunc(void* args){
	int i;
	MY_ARGS* my_args=(MY_ARGS*) args;
	int first = my_args->first;
	int last = my_args->last;
	int id = my_args->id;
	for(i=first; i

 

你可能感兴趣的:(小问题)