Linux多线程程序设计,(网络上流传的一道题)

来源:互联网 发布:淘宝订单贷款逾期 编辑:程序博客网 时间:2024/06/05 14:24

 有四个线程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 <sys/types.h>
#include 
<sys/stat.h>
#include 
<fcntl.h>
#include 
<pthread.h>
#include 
<stdio.h>
#include 
<errno.h>
#include 
<string.h>
#include 
<malloc.h>
#include 
<stdlib.h>
#include 
<unistd.h>    //usleep ,sleep
#define MY_THREAD_COUNT 4
#define MY_LOOP_COUNT  3
typedef 
struct
{
    
int loops;  //表示要循环写入文件的次数
    int fd;
    
int curData; //当前要写入文件的数字
    pthread_mutex_t mutex;
}
FILENODE,*LPFILENODE;

char *filenames[] = {"a.txt","b.txt","c.txt","d.txt"};
pthread_t pids[MY_THREAD_COUNT];
FILENODE filenodes[MY_THREAD_COUNT];
bool IsCompleted()
{
    
for(int i = 0; i < MY_THREAD_COUNT; i++)
    
{
        
if(filenodes[i].loops != MY_LOOP_COUNT)
        
return false;
    }

    
return true;
}

void* ThreadFunc(void* para)
{
   
int num = *(int*)para;
   printf(
"Loop thread id: %d  ",num);
   
char buf[50= {""};   
   
bool bExit = false;
   
while(!bExit)
   
{
       
if(IsCompleted())
          
break;           
       printf(
"thread id : %d begin loops files ",num);
       
for(int i = 0; i < MY_THREAD_COUNT; i++)
       
{
        
int rtn = pthread_mutex_trylock(&filenodes[i].mutex);
        
if(rtn == 0)
        
{
        
if(filenodes[i].loops >= MY_LOOP_COUNT)
        
{
            pthread_mutex_unlock(
&filenodes[i].mutex);
                    
continue;
        }

        
if(filenodes[i].curData == num)
        
{    
            sprintf(buf,
"%d:%d",num,filenodes[i].curData);   
            write(filenodes[i].fd,buf,strlen(buf));
                filenodes[i].curData 
+= 1;
        }

            
if(filenodes[i].curData > 4)
        
{
                     filenodes[i].curData 
= 1;
                     filenodes[i].loops
++;             
        }
    
        pthread_mutex_unlock(
&filenodes[i].mutex);
        }
   
       }

       usleep(
500000);
   }

   printf(
"thread id : %d, succeed exit! ",num);
   free(para);
}

int main()
{
   
int i = 0;    
   
for(i = 0;i<MY_THREAD_COUNT;i++)
   
{
    filenodes[i].fd 
= open(filenames[i],O_CREAT|O_WRONLY,S_IRUSR|S_IWUSR);
        filenodes[i].loops 
= 0;
        filenodes[i].curData 
= i+1;
        
int rtn = pthread_mutex_init(&filenodes[i].mutex,NULL);
    
int* para = (int*)malloc(sizeof(int));
    
*para = i+1;
        rtn 
= pthread_create(&pids[i],NULL,ThreadFunc,para);           
   }

   
for(i = 0;i<MY_THREAD_COUNT;i++)
   
{
       pthread_join(pids[i],NULL);
   }

   
for(int i = 0; i < MY_THREAD_COUNT;i++)
   
{
       
if(!filenodes[i].fd)
       
{
           close(filenodes[i].fd);
       }
           
   }

  
return 0;    
}

通过Shell>: g++ -g  -o Threads main.C -lpthread

生成可执行文件Threads,执行可执行文件后就可以查看结果。对于上面的题目,我做了一个扩冲,就是设定了循环的次数。