我不明白为什么我的代码会给我疯狂的输出,有时还会出现段错误(代码是由我编写的 08218722 以防万一我的大学检查抄袭)。
该代码在Linux Mint 14 中用C++编写,并使用
g++ -o code.exe code.cpp -lpthread
然后运行./code.exe
.
该代码应该生成一个随机字符向量(仅使用字符 a、b、c、d、e 和 f),最多 1000000,然后循环并计算每个字符的数量。这在我添加线程之前工作正常(测试非线程和线程之间的运行时间的分配的一部分)。所以我创建了 1000 个线程,它们被告知要添加 1000 个字符以添加到向量中。我在这里做错了什么?
更新 - 代码仍然输出一些疯狂的结果 - 现在它不显示字符而是某种方块
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <vector>
#include <algorithm>
#include <pthread.h>
#include <ctime>
using namespace std;
//Variable Declarations
const int length = 1000000; // length
const int packets = 1000; // packets length
const char chars[6] = {'a', 'b', 'c', 'd', 'e', 'f'}; // chars to choose
vector<char> charList(length); //vector of random charecter list
int charGroup[6] = {}; //stores char count
pthread_t threads[packets];
//Structure Declarations
struct dataStruct {
int start;
int end;
};
//Function Declarations
void *randomLetterGenerator(void * args); // Declaring function
// prints the vector
void outVector(char n)
{
cout << n;
}
void GroupVector(char n)
{
charGroup[n] = charGroup[n] + 1;
}
int main(){
cout << "Creating a Random Char Array" << endl;
cout << "using only letters ranging between a and f." << endl;
//srand(time(NULL)); // sets the time seed
clock_t start = clock();
for(int i=0;i<length/packets;i++) {
printf("\rPlease wait...%3d/%3d",i*packets,length);
//Created in packets
dataStruct ds;
ds.start = i * (length/packets);
ds.end = ds.start + (length/packets);
pthread_create(&threads[i], NULL, randomLetterGenerator, (void *)&ds);
}
for(int i=0;i<length/packets;i++) {
pthread_join(threads[i], NULL);
}
printf("\n"); //new line
//prints out the new char list
for_each(charList.begin(), charList.end(), outVector) ;
printf("\n"); //new line
//Counts and places in the correct array
for_each(charList.begin(), charList.end(), GroupVector) ;
int total = 0;
for (int i = 0; i < 6; i++) {
total += charGroup[chars[i]];
cout << chars[i] << " = " << charGroup[chars[i]] << endl;
}
cout << "\nTotal: " << total << endl;
clock_t ends = clock();
cout << "Run Time :"
<< (double) (ends - start) / CLOCKS_PER_SEC << endl;
pthread_exit(NULL);
return 0;
}
void * randomLetterGenerator(void * datastruct){
dataStruct ds = *((dataStruct *) datastruct);
int start = ds.start;
int end = ds.end;
srand( time(NULL) );
for(unsigned int c=start;c<end;c++){
int i = (int) (rand() % 6);
char rchar = chars[i];
//--pthread_mutex_lock (&mutex);
charList.at(c)= i;
//--charList.push_back(rchar);
//--pthread_mutex_unlock (&mutex);
}
pthread_exit(NULL);
}