【发布时间】:2019-08-08 07:32:53
【问题描述】:
如下所示,functionA 将传递一些参数并创建一个线程来执行一些计算并将结果存储到 ResultPool(全局)中以供以后使用。 functionA 将被调用几次,每次它传递不同的参数并创建一个新线程。所有的thread_id都会保存在全局变量中,在执行结束时,会从ThreadIdPool中取出thread_id并检查线程是否完成,然后从中输出结果结果池。下面的示例代码中省略了线程状态检查和输出结果。
我下面的代码是否是线程安全的,尤其是对于那些共享数据?我应该添加什么来防止灾难性故障吗?请指教
IntS threadCnt;
struct ThreadData
{
int td_tnum;
float td_Freq;
bool td_enablePlots;
int td_ifBin;
int td_RAT;
};
typedef struct ThreadData structThreadDt;
void *thread_A(void *td);
map<int, float> ResultPool;
map<int, pthread_t> ThreadIdPool;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
pthread_t thread_id[10];
void FunctionA(int tnum, float msrFrequency, bool enablePlots)
{
//Pass the value to the variables.
int ifBin;
int RAT;
/*
Some calculation here and the results are assigned to ifBin and RAT
*/
structThreadDt *td;
td =(structThreadDt *)malloc(sizeof(structThreadDt));
td->td_tnum = tnum;
td->td_Freq = msrFrequency;
td->td_enablePlots = enablePlots;
td->td_ifBin = ifBin;
td->td_RAT = RAT;
threadCnt = threadCnt+1;
pthread_create(&thread_id[threadCnt], NULL, thread_A, (void*) td);
//Store the thread id to be check for the status later.
ThreadIdPool[tnum]=thread_id[threadCnt];
}
void* thread_A(void* td)
{
int ifBin;
int RAT;
BoolS enablePlots;
FloatS msrFrequency;
IntS tnum;
structThreadDt *tds;
tds=(structThreadDt*)td;
enablePlots = tds->td_enablePlots;
msrFrequency = tds->td_Freq;
tnum = tds->td_tnum;
ifBin = tds->td_ifBin ;
RAT = tds->td_RAT;
/*
Do some calculation here with those ifBIN, RAT, TNUM and frequency.
*/
//Store the result to shared variable with mutex lock
pthread_mutex_lock( &mutex2 );
ResultPool[tnum] = results;
pthread_mutex_unlock( &mutex2 );
free(tds);
return NULL;
}
【问题讨论】:
-
在 C++ 程序中使用
malloc和free有什么原因吗?为什么不使用std::thread(这会简化很多事情)?如果你有ThreadIdPool映射,为什么你需要thread_id数组(你没有任何边界检查)? -
不幸的是,我使用的是不支持
std::thread的旧版 C++。我确实在执行结束时检查了线程完成情况,这发生在另一段代码中,我没有在这里显示。