您的位置:首页 > 运维架构 > Linux

linux线程4(google面试题)

2015-09-15 14:28 716 查看
题目:有四个线程1 2 3 4,线程1的功能就是输出1,线程2的功能就是输出2,以此类推.......现在有四个文件ABCD。初始都为空。现让四个文件呈如下格式:

A:1 2 3 4 1 2 ......  

B:2 3 4 1 2 3 ......

C:3 4 1 2 3 4 ......

D:4 1 2 3 4 1 ......

请设计程序。

现在只能输出一个文件,待改进。

#include <stdio.h>
#include <stdlib.h> //包含exit()
#include <pthread.h>
#include <string.h>
#include <fstream>
#include <iostream>
using namespace std;

#define NUM 4
#define LOOP 6 //循环次数

ofstream ofile[NUM];
int record[]={0,1,2,3};

struct myPara
{
int tid;
int fileIndex;
};

pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;

int n=0;
void *threadFun(void *arg);

int main()
{
int i=0;
char fileName[]="A.txt";
pthread_t tid[NUM];

fileName[0]='A';
ofile[0].open(fileName,ios::trunc);
for(i=0;i<4;i++)
{
pthread_create(&tid[i],NULL,threadFun,(void *)i);
}
for(i=0;i<NUM;i++)
pthread_join(tid[i],NULL);

return 0;
}

void *threadFun(void *arg)
{
long num=(long)arg;
int i=0;
for(;i<2;i++)
{
pthread_mutex_lock(&mutex);
while(num!=n)
pthread_cond_wait(&cond,&mutex);
printf("线程 %ld 正在向 %c 文件写入.\n",num+1,'A');
ofile[0]<<num+1<<" ";
n=(n+1)%NUM;
pthread_mutex_unlock(&mutex);
pthread_cond_broadcast(&cond);
}
return NULL;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: