c语言多线程pthread库概览

- pthread.h #man pthread

- pthread_t th; pthread_create(&th,NULL,a_func,NULL); #afunc :(void *)->(void*)

- main不等待线程的,主死线程也死

- pthread_join(th,NULL);等待线程th

 - 多线程跑时,不知道谁先走,线程可交叉执行

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void* myfunc(void* args){
	for(int i=0;i<10;i++){
		printf("myfunc + hello world\n");
	}
	return NULL;
}
void* othfunc(void* args){
	for(int i = 1; i< 10;i++){
		printf("othfunc + %d\n",i);
	}
	return NULL;
}

int main(int argc,char** argv){
	pthread_t th;
	pthread_t th1;
	pthread_create(&th,NULL,myfunc,NULL);
	pthread_create(&th1,NULL,othfunc,NULL);
	pthread_join(th,NULL);
	pthread_join(th1,NULL);
	return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void* myfunc(void* args){
	for(int i=0;i<10;i++){
		printf("myfunc + hello world\n");
	}
	return NULL;
}
void* othfunc(void* args){
	for(int i = 1; i< 10;i++){
		printf("othfunc + %d\n",i);
	}
	return NULL;
}

typedef struct {
	int first,second;
}Args;

void* cntfunc(void* args){
	int i, sum = 0;
	Args* two_args = (Args*) args;
	int first = two_args->first;
	int second = two_args->second;

	for(i = first;i<second;i++){
		sum += i;
	}
	printf("%d\n", sum);
	return NULL;
}

int main(int argc,char** argv){
	pthread_t th;
	pthread_t th1;
	pthread_create(&th,NULL,myfunc,NULL);
	pthread_create(&th1,NULL,othfunc,NULL);
	pthread_join(th,NULL);
	pthread_join(th1,NULL);

	Args arg = {0,2500};
	Args arg1 = {1110,5500};
	pthread_create(&th,NULL,cntfunc,&arg);
	pthread_create(&th1,NULL,cntfunc,&arg1);
	pthread_join(th,NULL);
	pthread_join(th1,NULL);

	return 0;
}

- 数据竞争时就要加锁

- pthread_mutex_t lock;

- pthread_mutex_init(&lock,NULL);

- 对代码段加锁

pthread_mutex_lock(&lock);

s++;

pthread_mutex_unlock(&lock);

 

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>



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

int main(int argc,char** argv){
	pthread_mutex_init(&lock,NULL);

	pthread_t th;
	pthread_t th1;
	pthread_create(&th,NULL,myfunc,NULL);
	pthread_create(&th1,NULL,myfunc,NULL);
	pthread_join(th,NULL);
	pthread_join(th1,NULL);
	printf("%d\n", s);

	return 0;
}

- it works,但是这好像没有用到多线程,因为一旦加上上面的锁,程序也只能按序执行

- gcc pth.c -lpthread -o main

- time ./main

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值