Linux开发——多线程管理

目录

线程

创建线程

线程退出

线程的私有数据

线程互斥:

条件变量

简单列子

读写锁

线程信号

线程属性


线程

获取线程tpid:syscall(SYS_gettid)   系统调用

创建线程

线程退出

线程的私有数据

线程互斥:

条件变量

简单列子

#include "stdio.h"
#include "stdlib.h"
#include "pthread.h"
#include "time.h"
#include <unistd.h>


#define BUFFER_SIZE 4
#define OVER (-1)

struct prodcons
{
	int buffer[BUFFER_SIZE];
	pthread_mutex_t lock;
	int readpos,writepos;
	pthread_cond_t notempty;
	pthread_cond_t notfull;
};

struct prodcons buffer;

void init(struct prodcons * prod)
{
	pthread_mutex_init(&prod->lock,NULL);
	pthread_cond_init(&prod->notempty,NULL);
	pthread_cond_init(&prod->notfull,NULL);
	prod->readpos = 0;
	prod->writepos = 0;
}
void put(struct prodcons * prod,int data)
{
	pthread_mutex_lock(&prod->lock);
	while((prod->writepos+1)%BUFFER_SIZE==prod->readpos)
	{
		printf("producer wait for not full\n");
		pthread_cond_wait(&prod->notfull,&prod->lock);
	}
	prod->buffer[prod->writepos] = data;
	prod->writepos++;
	if(prod->writepos >= BUFFER_SIZE)
		prod->writepos = 0;
	pthread_cond_signal(&prod->notempty);
	pthread_mutex_unlock(&prod->lock);
}
void * producer(void *data)
{
	int n;
	for (int i = 0; i < 5; ++i)
	{
		printf("producer sleep 1 second\n");
		sleep(1);
		printf("put thd %d product\n",i);
		put(&buffer,i);
	}
	for (int i = 5; i < 10; ++i)
	{
		printf("producer sleep 3 second\n");
		sleep(3);
		printf("put thd %d product\n",i);
		put(&buffer,i);
	}
	put(&buffer,OVER);
	printf("producer stop!\n");
	return NULL;
}
int get(struct prodcons * prod)
{
	pthread_mutex_lock(&prod->lock);
	while((prod->readpos)%BUFFER_SIZE == (prod->writepos)){
		printf("consumer wait producer!!!%d---%d\n",prod->readpos,prod->writepos);
		pthread_cond_wait(&prod->notempty,&prod->lock);
	}
	int value = prod->buffer[prod->readpos];
	prod->readpos++;
	if(prod->readpos >= BUFFER_SIZE)
	{
		prod->readpos = 0;
	}
	pthread_cond_signal(&prod->notfull);
	pthread_mutex_unlock(&prod->lock);
	return value;
}
void *consumer(void * data)
{
	int a;
	while(1){
		sleep(1);
		a = get(&buffer);
		if(a==-1){
			break;
		}
	}
	return NULL;
}

int main(int argc, char const *argv[])
{
	pthread_t th_a,th_b;
	void * retval;
	init(&buffer);
	pthread_create(&th_a,NULL,producer,0);
	pthread_create(&th_b,NULL,consumer,0);

	pthread_join(th_a,&retval);
	pthread_join(th_b,&retval);
	return 0;
}

读写锁

线程信号

绑定是共享的,屏蔽是分开的

线程属性

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值