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;
}
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;
}
相关文章推荐
- 史上最详细的虚拟机上安装Linux教程
- linux命令行安装matlab
- Linux 环境下思源黑体字体与 Java 之间的兼容性问题的解决
- linux下使用ramdisk的一点认识
- centos7下使用yum安装mysql
- Linux鸟哥私房菜学习笔记--第九章
- Linux 下安装ffmpeg(xlib264 yams)
- Linux 下ffmpeg的安装(xlib264 yams)
- CentOS 安装python MySQLdb模块
- 左右GNU Linux企业加密文件系统 eCryptfs简介
- linux挂载光盘
- unix/linux共享内存应用与陷阱
- linux下彻底卸载MySQL
- 马哥-51CTO-Linux培训-0905-Linux任务计划
- window程序移植到linux(二)
- 学习重新编译Linux内核
- Linux环境下,traceroute返回一系列*原因分析
- CentOS6.5手动升级gcc4.8.2
- 马哥linux学习(linux上的包管理)
- linux下weblogic 12c 节点管理器配置