使用多线程和sleep函数生成字符串的伪随机排列

     据说是阿里的笔试题,手写还是有难度的,不过思想倒是很简单,无意看到的,原创可是原创_他 ,这小子很自恋,喜欢给自己的博文做评论。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<pthread.h>
#include<unistd.h>
/**********************
 *程序在不用系统的random函数,生成随机的字符串
 *同时创建7个线程,每个线程传入一个参数i,既是
 *字符串数组中的第i各位置与第零个位置的字母交换
 *不确定那个线程会先到,所以产生的串是随机排列的
 *对共有的资源chs[]加锁,防止一个字符出现两次
 * ****************************/

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

char chs[7] ={'A', 'B', 'C', 'D', 'E', 'F', 'G'};
void *th_fun(void* arg)
{
	int i = *((int *)arg);
	char temp;
	pthread_mutex_lock(&mutex);
	temp = chs[i];
	chs[i] = chs[0];
	chs[0] = temp;
	pthread_mutex_unlock(&mutex);

	sleep(1);
	return ((void *)0);
}

int main(void){

	pthread_t th[7];
	int i = 0;

	while(i<7){
		if(0!=pthread_create(&th[i], NULL, th_fun, (void *)&i)){
			fprintf(stderr, "pthread %d:%s\n", i, strerror(errno));
			exit(1);
		}
		i++;
	}
	for(i=0;i<7;i++){
		pthread_join(th[i], NULL);
	}

	printf("chs:%s\n", chs);

	return 0;

}

强烈建议,建议CSDN编辑器添加对Tab键的使用功能。TAB TAB


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值