编写一个程序,程序会启动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; }