Linux开发——多线程管理

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_25490573/article/details/102646575

线程

获取线程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;
}

读写锁

线程信号

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

线程属性

猜你喜欢

转载自blog.csdn.net/qq_25490573/article/details/102646575