【发布时间】:2020-02-25 01:14:49
【问题描述】:
我有一个名为“Vector”的类,默认情况下它包含 10.000 个元素,这些元素在任何时候都必须具有相同的值。这个类已经过测试并且可以工作。因此,我使用类中的方法 setAndTest() 来设置所有元素的值,然后立即检查 Vector 对象是否一致(所有向量元素都具有相同的值)。
在一个新文件“main.cpp”中,我创建了两个函数:writer() 和main()。
writer() 创建用户定义数量的 writer 线程(介于 1 和 100 之间),每个线程都有自己唯一的 id。每个 writer 每秒将共享 Vector 对象设置和测试为其 id。如果编写器在共享 Vector 对象中检测到不一致,setAndTest() 将返回 false 并应打印以下错误消息:Error with thread #id
然而,在 99% 的情况下,它会输出 Success with thread #id,而我预计两者之间会有更多的变化。
main.cpp 文件中包含的头文件:
#include <iostream>
#include "Vector.hpp"
#include <pthread.h>
#include <unistd.h>
using namespace std;
向量对象和 writer() 函数:
Vector VecObj; //The Vector object (Defined in global scope)
void* writer(void *threadid)
{
int threadid_ = *(int *)(threadid);
if(VecObj.setAndTest(threadid_))
{
std::cout << "\nSuccess with thread " << threadid_ << endl;
}else
{
std::cout << "\nError with thread " << threadid_ << endl;
}
return NULL;
}
主要功能:
int main()
{
start:
int numOfThreads = 1;
std::cout << "Enter amount of threads (must be between 1 & 100): ";
std::cin >> numOfThreads;
if(0 < numOfThreads && numOfThreads <= 100){
std::cout << "You entered " << numOfThreads << " threads" << endl;
}else{
std::cout << "Amount of threads must be between 1 & 100" << endl;
goto start;
}
pthread_t threadcreator[numOfThreads];
for(int i = 0; i < numOfThreads; i++){
pthread_create(&threadcreator[i], NULL, writer, &i);
sleep(1);
}
for(int i = 0; i < numOfThreads; i++){
pthread_join(threadcreator[i], NULL);
}
}
矢量类(Vector.hpp):
#ifndef VECTOR_HPP_
#define VECTOR_HPP_
#include <pthread.h>
using namespace std;
//=======================================================
// Class: Vector
// contains a size_-size vector of integers.
// Use the function setAndTest to set all elements
// of the vector to a certain value and then test that
// the value is indeed correctly set
//=======================================================
class Vector
{
public:
Vector(unsigned int size = 10000) : size_(size)
{
vector_ = new int[size_];
set(0);
}
~Vector()
{
delete[] vector_;
}
bool setAndTest(int n)
{
set(n);
return test(n);
}
private:
void set(int n)
{
for(unsigned int i=0; i<size_; i++) vector_[i] = n;
}
bool test(int n)
{
for(unsigned int i=0; i<size_; i++) if(vector_[i] != n) return false;
return true;
}
int* vector_;
unsigned int size_;
};
#endif
【问题讨论】:
-
"这个类已经过测试并且可以工作。":这个类明显违反了rule-of-three。 (尽管据我所知,这对于这种特定情况并不重要。)
-
您有什么理由不使用
<thread>的 C++11 线程工具吗?
标签: c++ linux multithreading class pointers