多线程例程

1.子线程 循环打印10次,主线程循环打印100次,接着子线程循环10次,如此循环50次,请写出代码

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


#define LOOPNUM 50
#define MAINLOOPNUM 100
#define CHILDLOOPNUM 10

int num = 0;
int param_0 = 0;
int param_1 = 1;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void* threadFunc(void * arg)
{
    for (int i = 0; i < LOOPNUM; i++)
    {
        pthread_mutex_lock(&mutex);

        while (num != param_0)
        {
            pthread_cond_wait(&cond, &mutex);
        }

        printf("child:\n");
        for (int i = 0; i < CHILDLOOPNUM; i++)
        {
            printf("%d", i);
        }
        printf("\n");

        num = (num + 1) % 2;
        
        pthread_mutex_unlock(&mutex);
        pthread_cond_signal(&cond);
    }
    
    return (void *)0;
}

int main(int argc, char **argv)
{
    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cond, NULL);
    void *ret = NULL;
    pthread_t tid_child;

    pthread_create(&tid_child, NULL, threadFunc, NULL);

    for (int i = 0; i < LOOPNUM; i++)
    {
        pthread_mutex_lock(&mutex);

        while (num != param_1)
        {
            pthread_cond_wait(&cond, &mutex);
        }
        
        printf("main:\n");
        for (int i = 0; i < MAINLOOPNUM; i++)
        {
             printf("%d", i); 
        }
        printf("\n");
        
        num = (num + 1) % 2;
        
        pthread_mutex_unlock(&mutex);
        pthread_cond_signal(&cond);
    }

    pthread_join(tid_child, &ret);
    
    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);
    return 0;

}

2.创建三个线程A,B,C,轮流打印ABC10次

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

#define LOOPNUM 10
#define THREAD_NUM 3

int num = 0;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void* threadFunc(void * arg)
{
	int val = *(int *)arg;
	for (int i = 0; i < LOOPNUM; i++)
	{
		pthread_mutex_lock(&mutex);
		
		while (num != val)
		{
			pthread_cond_wait(&cond, &mutex);
		}
		
		printf("%c", 'A' + val);
		
		num = (num + 1) % THREAD_NUM;
		
		pthread_mutex_unlock(&mutex);
		pthread_cond_broadcast(&cond);
	}
	
	return (void *)0;
}

int main(int argc, char **argv)
{
	pthread_mutex_init(&mutex, NULL);
	pthread_cond_init(&cond, NULL);
	void *ret = NULL;
	pthread_t tid[THREAD_NUM];
	int tidNum[3] = {0, 1, 2};
	for (int i = 0; i < THREAD_NUM; i++)
	{
		pthread_create(&tid[i], NULL, threadFunc, (void *)(tidNum + i));	
	}

	for (int i = 0; i < THREAD_NUM; i++)
	{
		pthread_join(tid[i], &ret);
	}
	
	printf("\n");
	pthread_mutex_destroy(&mutex);
	pthread_cond_destroy(&cond);
	
	return 0;
	
}

3.多个生产者单个消费者,环形共享缓冲区问题。(基于内存信号量)

该问题中需要维持的三个条件为:

(1)缓冲区为空时,消费者不能从中获取条目(移除一个条目)

(2)缓冲区满时,生产者不能往缓冲区中放入一个条目

(3)共享变量描述的当前缓冲区的状态(下标,计数,数据指针等),都必须保护起来。

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <algorithm>
#include <unistd.h>

#define BUFFERSIZE 10
#define MAX_THREADS 100

int nItems;
int nProducers;

typedef struct{
	int buff[BUFFERSIZE];
	int nput;
	int nputval;
	sem_t mutex;
	sem_t emptySlot;
	sem_t storeSlot;	
}T_Shared;

T_Shared g_shared;

void* producer(void *arg);
void* consumer(void *arg);

int main(int argc, char **argv)
{
	int count[MAX_THREADS];
	pthread_t tid_producer[MAX_THREADS], tid_consumer;
	
	nItems = atoi(argv[1]);
	nProducers = std::min(atoi(argv[2]), MAX_THREADS);
	
	sem_init(&g_shared.mutex, 0, 1);
	sem_init(&g_shared.emptySlot, 0, BUFFERSIZE);
	sem_init(&g_shared.storeSlot, 0, 0);
						  
	for (int i = 0; i < nProducers; i++)
	{
		count[i] = 0;
		pthread_create(&tid_producer[i], NULL, producer, &count[i]);
	}
						 
	pthread_create(&tid_consumer, NULL, consumer, NULL);
						  
	for (int i = 0; i < nProducers; i++)
    {
		pthread_join(tid_producer[i], NULL);
		printf("count[%d] = %d\n", i, count[i]);
    }
    pthread_join(tid_consumer, NULL);
			
	sem_destroy(&g_shared.mutex);
	sem_destroy(&g_shared.emptySlot);
	sem_destroy(&g_shared.storeSlot);
						  
	return 0;
}
						  
void* producer(void * arg)
{
	for (; ;)
	{
		sem_wait(&g_shared.emptySlot);
		sem_wait(&g_shared.mutex);
		
		if (g_shared.nput >= nItems)
		{
			sem_post(&g_shared.emptySlot);
			sem_post(&g_shared.mutex);
			return NULL;
		}
		g_shared.buff[g_shared.nput % BUFFERSIZE] = g_shared.nputval;
		g_shared.nput++;
		g_shared.nputval++;
		
		sem_post(&g_shared.mutex);
		sem_post(&g_shared.storeSlot);
		*((int *)arg) += 1;
	}
	return (void *)0;
}
						  
void* consumer(void *arg)
{
	for (int i = 0; i < nItems; i++)
	{
		sem_wait(&g_shared.storeSlot);
		sem_wait(&g_shared.mutex);
		
		if (g_shared.buff[i % BUFFERSIZE] != i)
		{
			printf("error:buff[%d] = %d\n", i, g_shared.buff[i % BUFFERSIZE]);	
		}
		
		sem_post(&g_shared.mutex);
		sem_post(&g_shared.emptySlot);	
	}
	
	return (void *)0;
}

4.多个生产者多个消费者,环形共享缓冲区问题。(基于内存信号量)

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <algorithm>
#include <unistd.h>
 
#define BUFFERSIZE 10
#define MAX_THREADS 100
 
int nItems;
int nProducers, nConsumers;
 
typedef struct{
	int buff[BUFFERSIZE];
	int nput;
	int nputval;
    int nget;
    int ngetval;
	sem_t mutex;
	sem_t emptySlot;
	sem_t storeSlot;	
}T_Shared;
 
T_Shared g_shared;
 
void* producer(void *arg);
void* consumer(void *arg);
 
int main(int argc, char **argv)
{
	int countP[MAX_THREADS], countC[MAX_THREADS];
	pthread_t tid_producer[MAX_THREADS], tid_consumer[MAX_THREADS];
	
	nItems = atoi(argv[1]);
	nProducers = std::min(atoi(argv[2]), MAX_THREADS);
    nConsumers = std::min(atoi(argv[3]), MAX_THREADS);
	
	sem_init(&g_shared.mutex, 0, 1);
	sem_init(&g_shared.emptySlot, 0, BUFFERSIZE);
	sem_init(&g_shared.storeSlot, 0, 0);
						  
	for (int i = 0; i < nProducers; i++)
	{
		countP[i] = 0;
		pthread_create(&tid_producer[i], NULL, producer, &countP[i]);
	}

    for (int i = 0; i < nConsumers; i++)
    {
        countC[i] = 0;
        pthread_create(&tid_consumer[i], NULL, consumer, &countC[i]);
    }
						  
	for (int i = 0; i < nProducers; i++)
    {
		pthread_join(tid_producer[i], NULL);
		printf("countP[%d] = %d\n", i, countP[i]);
    }

    for (int i = 0; i < nConsumers; i++)
    {
        pthread_join(tid_consumer[i], NULL);
        printf("countC[%d] = %d\n", i, countC[i]);
    }
			
	sem_destroy(&g_shared.mutex);
	sem_destroy(&g_shared.emptySlot);
	sem_destroy(&g_shared.storeSlot);
						  
	return 0;
}
						  
void* producer(void * arg)
{
	for (; ;)
	{
		sem_wait(&g_shared.emptySlot);
		sem_wait(&g_shared.mutex);
		
		if (g_shared.nput >= nItems)
		{
            sem_post(&g_shared.storeSlot);
			sem_post(&g_shared.emptySlot);
			sem_post(&g_shared.mutex);
			return NULL;
		}
		g_shared.buff[g_shared.nput % BUFFERSIZE] = g_shared.nputval;
		g_shared.nput++;
		g_shared.nputval++;
		
		sem_post(&g_shared.mutex);
		sem_post(&g_shared.storeSlot);
		*((int *)arg) += 1;
	}
	return (void *)0;
}
						  
void* consumer(void *arg)
{
    int i = 0;
	for (; ;)
	{
        sem_wait(&g_shared.storeSlot);
        sem_wait(&g_shared.mutex);

        if (g_shared.nget >= nItems)
        {
            sem_post(&g_shared.storeSlot);
            sem_post(&g_shared.mutex);
            return NULL;
        }

        i = g_shared.nget % BUFFERSIZE;
        if (g_shared.buff[i] != g_shared.ngetval)
        {
            printf("error:buff[%d] = %d\n", i, g_shared.buff[i]);	
        }

        g_shared.nget++;
        g_shared.ngetval++;
        sem_post(&g_shared.mutex);
        sem_post(&g_shared.emptySlot);	
        *((int *)arg) += 1;
	}
	
	return (void *)0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值