我正在实现带有类的线程示例,并将参数作为结构传递给线程。我为四个线程中的每一个初始化类成员,但是不知何故一个类成员没有被初始化,而是被初始化为垃圾值。我尝试将线程数减少到3,但是同一类成员正在初始化为垃圾值。
在下面的Dining Philosopher示例尝试中,Philosopher(thread)1 fork2被初始化为垃圾值。
#include <iostream>
#include <stdio.h>
#include "PhilOne.h"
#include <pthread.h>
using namespace std;
#define NUM_PHIL 4
struct phil_data {
int thread_id;
int fork1;
int fork2;
};
void *StartPhil(void *threadarg){
struct phil_data *my_data;
my_data = (struct phil_data *) threadarg;
int tid = my_data->thread_id;
int my_fork1 = my_data->fork1;
int my_fork2 = my_data->fork2;
cout << "Hello World! I am Philosopher number, " << tid << endl;
cout << "My fork1 is:" << my_fork1 << endl;
cout << "My fork2 is:" << my_fork2 << endl;
PhilOne phil[tid];
phil[tid].waitForForks();
phil[tid].eat();
phil[tid].releaseForks();
phil[tid].think();
std::cout<<std::endl;
pthread_exit(NULL);
}
int main(){
pthread_t threads[NUM_PHIL];
struct phil_data td[NUM_PHIL];
int rc;
int i;
for (i=0;i<NUM_PHIL;i++){
//pthread_mutex_lock(&lock);
cout << "main(): creating Philosopher," << i << endl;
td[i].thread_id = i;
switch (i){
case 0:
{
td[i].fork1=0;
td[i].fork2=1;
break;
}
case 1:
{
td[i].fork1=1;
td[i].fork2=5;
break;
}
case 2:
{
td[i].fork1=2;
td[i].fork2=3;
break;
}
case 3:
{
td[i].fork1=3;
td[i].fork2=0;
break;
}
default:
break;
}
rc = pthread_create(&threads[i],NULL,StartPhil,(void *)&td[i]);
if (rc){
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
}
pthread_exit(NULL);
}
下面是PhilOne.cpp
#include "PhilOne.h"
#include <iostream>
using namespace std;
PhilOne::PhilOne(){
//ctor
}
PhilOne::~PhilOne(){
//dtor
}
int PhilOne::eat(){
cout << "Eating ...." << endl;
sleep(2);
return 0;
}
int PhilOne::releaseForks()
{
std::cout << "Released forks ...." <<std::endl;
return 0;
}
int PhilOne::think()
{
std::cout << "Thinking...." <<std::endl;
sleep(1);
return 0;
}
int PhilOne::waitForForks()
{
std::cout << "Waiting for forks...." <<std::endl;
sleep(3);
return 0;
}
答案 0 :(得分:2)
我无法重现您的结果,但是程序中似乎存在一些未定义的行为。
PhilOne phil[tid];
phil[tid].waitForForks();
声明一个PhilOne对象数组的目的是什么?第二行将访问数组之后的对象。我认为您只需要
PhilOne phil;
phil.waitForForks();
尝试解决此问题,它可能会解决您的问题。