我似乎很难理解下面的代码有什么问题。该程序运行正确,但在行
startCounter.join();
我的程序似乎崩溃了,错误代码为 EXC_BAD_ACCESS(代码=13,地址=0x0)。我正在使用 XCode。
直到该行正常工作为止的所有内容;当另一个线程无限期地递增该值时,程序每秒打印出 n 的值。我究竟做错了什么?
#include <iostream>
#include <boost/thread.hpp>
boost::mutex mtx;
class Worker
{
public:
Worker(int n);
void increment();
void printValue();
private:
int n;
};
int main()
{
Worker test(5);
boost::thread startCounter(boost::bind(&Worker::increment, &test));
std::cout << "Increment Thread Started..." << std::endl;
boost::thread startPrinter(boost::bind(&Worker::printValue, &test));
std::cout << "Print Thread Started..." << std::endl;
startPrinter.join();
startCounter.join();
std::cout << "Program Complete." << std::endl;
return EXIT_SUCCESS;
}
Worker::Worker(int n) : n(n)
{
std::cout << "Initial Value: " << n << std::endl;
}
void Worker::increment()
{
for (int i = 0; i < 60000000; i++) {
boost::lock_guard<boost::mutex> lock(mtx);
n = i;
}
std::cout << "Increment Thread Finished. Final Value: " << n << "." << std::endl;
}
void Worker::printValue()
{
for (int i = 0; i < 10; i++) {
{
boost::lock_guard<boost::mutex> lock(mtx);
std::cout << "Current value: " << n << std::endl;
}
boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
}
std::cout << "Print Thread Finished." << std::endl;
}
非常感谢!