【发布时间】:2014-09-15 10:37:53
【问题描述】:
我想用一个线程创建一个长度为 50 的数组,完成后我想用第二个线程在每 X 秒内打印一些第一个值。同时第一个线程可以计算下一个数组。
在我尝试将计算数组中的一些值复制到一些临时变量中之前,这些线程都是有效的。我没有编译错误,但是当我运行程序时,我得到了一个 Windows 崩溃消息。
没有线程,double *newarray(); 函数可以工作。返回一个手动分配并填充数据的数组。
我在这里错过了什么?
线程 1:
double *newarray();
void *computingU(void *)
{
double * U_tmp;
while (true)
{
pthread_mutex_lock( &mutexU );
memcpy(U_tmp,newarray(),sizeof(double)*Ulenght);
while (!Usent);
Usent = false;
memcpy(Ucmd,U_tmp,sizeof(double)*Ulenght);
pthread_mutex_unlock( &mutexU );
Ucomputed = true;
}
}
线程 2:
void *sendingCMD(void * ) {
double * U_tmp;
while (true)
{
while (!Ucomputed);
Ucomputed = false;
pthread_mutex_lock( &mutexU );
memcpy(U_tmp,Ucmd,sizeof(double)*Ulenght);
pthread_mutex_unlock( &mutexU );
Usent = true;
for (int i = 0; i<Ulenght; i++)
{
printf("i= %d, u= %f", i, U_tmp[i]);
sleep(sleepTime) ;
}
}
}
主要:
#include <pthread.h>
#include <time.h>
#include <math.h>
#include <unistd.h>
using namespace std;
bool Ucomputed = false, Usent = true;
double * Ucmd;
pthread_mutex_t mutexU = PTHREAD_MUTEX_INITIALIZER;
unsigned int Ulenght = 1;
int sleepTime = 1;
int main( void )
{
#ifdef DEBUG_THREAD
int rc1, rc2;
pthread_t thread1, thread2;
/* Create independent threads each of which will execute functionC */
if( (rc1=pthread_create( &thread1, NULL, &computingU, NULL)) ) {
printf("Thread creation failed: %d\n", rc1);
}
if( (rc2=pthread_create( &thread2, NULL, &sendingCMD, NULL)) )
{
printf("Thread creation failed: %d\n", rc2);
}
#endif //
sleep(10);
while (true);
}
【问题讨论】:
-
为什么要在
computingU中两次锁定互斥锁? -
这是我复制代码时的错误。
标签: c++ arrays windows multithreading pthreads