(阿里笔试)使用多线程和sleep函数生成字符串的伪随机排列

写在前面:这是阿里巴巴2014校园招聘2013.9.22杭州站的笔试题目,下面分别给出windows和linux平台的c/c++版本。

1. C/C++(windows平台)

//生成字符串的伪随机排列
#include 
#include 
#include 
#include 

unsigned int __stdcall Fun(void* pM)
{
	Sleep(10);
	char ch = *(char*)pM;
	putchar(ch);
	return 0;
}

int main()
{
	std::string str = "abcdefg";
	HANDLE handle[7];
	for(int i = 0; i < 7; ++i)
		handle[i] = (HANDLE)_beginthreadex(NULL,0,Fun,&str[i],0,NULL);
	WaitForMultipleObjects(7,handle,TRUE,INFINITE);
	return 0;

}

2. C/C++(Linux平台)

注意编译连接时需要链接pthread库,即g++ XX.cpp -o XX -lpthread

#include 
#include 
#include 

void* thread(void* v)
{
	char ch = *(char*)v;
	sleep(1);
	putchar(ch);
}

int main()
{
	pthread_t id[7];
 	int i ,ret;
	char str[] = "abcdefg";
	for(i = 0; i < 7; ++i)
	{
		ret = pthread_create(&id[i],NULL,thread,&str[i]);
		if(0 != ret)
		{
			printf("create pthread error\n");
			i--;
		}
	}
	for(i = 0; i < 7; ++i)
		pthread_join(id[i],NULL);
	printf("\n");
	return 0;
		
	
}



你可能感兴趣的:(笔试面试,C++)