Google多线程面试题: 4个线程向4个文件里写入数据, 每个线程只能写一个值(待更新)

编写一个程序,程序会启动4个线程,向4个文件A,B,C,D里写入数据,每个线程只能写一个值。 
    线程A:只写A
    线程B:只写B 
    线程C:只写C 
    线程D:只写D 

4个文件A,B,C,D。 

程序运行起来,4个文件的写入结果如下: 
    A:ABCDABCD... 
    B:BCDABCDA... 
    C:CDABCDAB... 

D:DABCDABC...

比较简单的实现如下,但是并没有实现正真的并发,后续待补充每个线程有自己的可写文件队列,从队列取文件,写入,然后把文件加到下一个线程的可写队列。

#include <stdio.h> #include <pthread.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #define N 4 int fds[N] = {0}; int nums = 0; char filenames[][2] = {"A", "B", "C", "D"}; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond   = PTHREAD_COND_INITIALIZER; void *routine(void *arg) {     int i = (int)arg;     int j;     int k;     char s[2] = {0};     for(j = 0; j < 100; j++){         pthread_mutex_lock(&mutex);         while (nums % 4 != i)             pthread_cond_wait(&cond, &mutex);         k = (nums - nums / 4) % 4;         nums = (nums + 1) % 16;         s[0] = 'A' + i;         write(fds[k], s, 1);         pthread_mutex_unlock(&mutex);         pthread_cond_broadcast(&cond);       }     return NULL; } int main() {     int i = 0;     pthread_t tid[N];      for(i = 0; i < 4; i++)         if((fds[i] = open(filenames[i], O_WRONLY|O_TRUNC|O_CREAT, S_IRWXU|S_IRGRP)) == -1)             return -1;      for(i = 0; i < 4; i++)         pthread_create(tid + i, NULL, routine, i);     for(i = 0; i < 4; i++)         pthread_join(tid[i], NULL);     for(i = 0; i < 4; i++)         close(fds[i]);     return 0; }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值