• linux C++多线程操作文件&输出加锁


    下述demo将指定目录下文件存入vector,然后一分为二交给两个线程(threadTask1,threadTask2)去分别处理,对输出函数printDirent加锁防止紊乱。

    #include <iostream>
    #include <string>
    #include <sys/types.h>
    #include <dirent.h>
    #include <unistd.h>
    #include <stdio.h>
    #include <fstream>
    #include <iomanip>
    #include <ctime>
    #include <stdio.h>
    #include <stdlib.h>
    #include <pthread.h>
    #include <unistd.h>
    #include <list>
    #include <numeric>
    #include <algorithm>
    #include <vector>
    
    static pthread_mutex_t testlock;
    using namespace std; 
    void *threadTask1(void *ptr);
    void *threadTask2(void *ptr);
    typedef vector<dirent> VECTORDIRENT;
    VECTORDIRENT listDirent;
    VECTORDIRENT::iterator iter; 
    void printStr(string buff);
    void printDirent(struct dirent ptrTest);
    
    void *threadTask1(void *ptr)
    {
    	int vectorI=0;
    	int vectorLen = listDirent.size()/2;
    	int count=0;
            for(;vectorI<vectorLen;vectorI++)
            {
        	printDirent(listDirent[vectorI]);
        	count++;
    	}  
    }
    
    void *threadTask2(void *ptr)
    {
    	int vectorI=listDirent.size()/2;
    	int vectorLen = listDirent.size();
    	int count=0;
            for(;vectorI<vectorLen;vectorI++)
            {
        	printDirent(listDirent[vectorI]);
        	count++;
    	}
    }
    
    
    void printDirent(struct dirent ptrTest){
    	pthread_mutex_lock(&testlock);
    	cout<<ptrTest.d_name<<endl;
    	pthread_mutex_unlock(&testlock);
    	
    }
    
    int main(void)
    {
        DIR    *dirTest;
        struct    dirent    *ptrTest;
        string testFolderPathName = "/home/undoner/";
        dirTest = opendir(testFolderPathName.data()); ///open the dir
        int fileCount = 0;
        while((ptrTest = readdir(dirTest)) != NULL) ///read the list of this dir
        {   
    		if(ptrTest->d_type==8){
    			listDirent.push_back(*ptrTest);
    		}
        }
        cout<<listDirent.size()<< endl; 
        cout<<"listDirent.begin()--- listDirent.end():"<<endl; 
        for (iter = listDirent.begin(); iter != listDirent.end(); ++iter) {
        	cout << iter->d_name << " "; 
        }
        pthread_t thread1,thread2;
    	int ret1,ret2;
    	ret1=pthread_create(&thread1,NULL,threadTask1,NULL);
    	ret2=pthread_create(&thread2,NULL,threadTask2,NULL);
    	//ret3=pthread_create(&thread3,NULL,thread,NULL);
    	if(ret1!=0){
    	printf ("Create pthread error!
    ");
    	exit (1);
    	}
    	if(ret2!=0){
    	printf ("Create pthread error!
    ");
    	exit (1);
    	}
    	pthread_join(thread1,NULL);
    	pthread_join(thread2,NULL);	
    	return 0;
    }
    


  • 相关阅读:
    小程序隐藏或自定义 scroll-view滚动条
    小程序携带参数(单个或多个)跳转页面(实例)
    小程序接收from表单数据(实例)
    js返回上一页
    项目部署到线上后台进不去
    微信小程序取消button边框线
    阿里iconfont图库官网网址
    php 发送邮件(实例)
    PHP 数组序列化,转为字符串
    面向对象的设计原则
  • 原文地址:https://www.cnblogs.com/wuyida/p/6300870.html
Copyright © 2020-2023  润新知