#include <iostream>
#include <stdlib.h>
#include <pthread.h>
#include <fstream>
#include <sstream>
#include <mutex>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <vector>
using namespace std;
#define NUM_THREADS 2
pthread_mutex_t mutexChild;
pthread_cond_t condChild;
vector<int> vect;
void openfile(ifstream&, string);
void* childthread(void *args)
{
ifstream inFile;
openfile(inFile, "Fruits.txt");
string line;
pthread_mutex_lock(&mutexChild);
int countt = 0;
int lines = 0;
int total = 0;
while (!inFile.eof())
{
getline(inFile, line);
countt = 0;
for (int i = 0; i < line.size(); i )
if ((line[i] >= 'A' && line[i] <= 'Z')
|| (line[i] >= 'a' && line[i] <= 'z'))
{
countt ;
}
lines ;
vect.push_back(countt);
}
pthread_mutex_unlock(&mutexChild);
pthread_exit(NULL);
}
void* parentthread(void *args)
{
ifstream inFile;
openfile(inFile, "Fruits.txt");
string line;
pthread_mutex_lock(&mutexChild);
int lines = 0;
int total = 0;
int countt = 0;
while (!inFile.eof())
{
getline(inFile, line);
for (int i = 0; i < vect.size(); i )
cout << vect[i] << endl;
}
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
pthread_t threads;
int thrd1;
//int i;
int thrd2;
pthread_mutex_init(&mutexChild, NULL);
thrd1 = pthread_create(&threads, NULL, childthread, NULL);
if (thrd1)
{
cout << "Error:unable to create thread," << thrd1 << endl;
exit(-1);
}
pthread_t threads2;
thrd2 = pthread_create(&threads2, NULL, parentthread, NULL);
if (thrd2)
{
cout << "Error:unable to create thread," << thrd2 << endl;
exit(-1);
}
// pthread_join(threads,NULL);
// pthread_join(threads2, NULL);
//threads.join();
///threads2.join();
pthread_mutex_destroy(&mutexChild);
pthread_cond_destroy(&condChild);
pthread_exit(NULL);
}
void openfile(ifstream &inFile, string fname)
{
inFile.open(fname);
if (inFile.is_open())
{
// cout << "Successfully opened File" << endl;
}
}
當我只需要列印一次時,我的子執行緒會繼續列印輸出 8 次。我的 txt 檔案中有 8 行,所以我猜這就是它列印輸出 8 次的原因。誰能告訴我它為什么會這樣以及我如何改變它。我也知道為什么要執行此任務更簡單,但我需要使用 posix 執行緒交換資料。它的列印像這樣 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 8 次我只需要 1 2 3 4 5 6 7 8
uj5u.com熱心網友回復:
while (!inFile.eof())
{
getline(inFile, line);
for (int i = 0; i < vect.size(); i )
cout << vect[i] << endl;
}
為檔案中的每一行列印vector一次內置子執行緒的內容(有點。請參閱Why is iostream::eof inside a loop condition (ie `while (!stream.eof())`)被認為是錯誤的?)。這不是你想要的。似乎不需要在這里閱讀檔案。子執行緒已經讀取了檔案并完成了所有的vector組裝作業。
解決眼前的問題,重復列印資料,您所需要的只是
for (int i = 0; i < vect.size(); i )
cout << vect[i] << endl;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/425695.html
上一篇:C 中的物件讀寫多載
