【发布时间】:2017-08-01 22:52:06
【问题描述】:
我正在尝试完成一个程序,该程序使用多个线程 (3) 来分发 4000 美元的假设奖学金。每次线程处理时,它都会“锁定”“临界区”并阻止其他线程从总和中取出它们的块。每次访问时,线程都将收取剩余“奖学金”资金的 25%。输出是每个线程在获得奖学金时所花费的数量。
到目前为止,我的程序似乎正在处理正确的输出,但是当它到达最后时,似乎有一个问题。每个进程/线程都会到达一个它不会终止或退出的点,程序就会变得停滞不前并且无法完成。我觉得线程正在处理但不满足终止条件(奖学金全部消失)。最后一个函数 totalCalc() 永远不会到达。有没有人看到我没有看到的任何东西,这可以帮助缓解这个问题或推动程序完成?
#include <stdio.h>
#include <pthread.h>
#include <math.h>
#define PERCENTAGE 0.25
pthread_mutex_t mutex; // protecting critical section
int scholarship = 4000,
total = 0;
void *A();
void *B();
void *C();
void *totalCalc();
int main(){
pthread_t tid1,
tid2,
tid3;
//pthread_setconcurrency(3);
pthread_create(&tid1, NULL, (void *(*)(void *))A, NULL );
pthread_create(&tid2, NULL, (void *(*)(void *))B, NULL );
pthread_create(&tid3, NULL, (void *(*)(void *))C, NULL );
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_join(tid3,NULL);
totalCalc();
return 0;
}
void *A(){
float result;
while(scholarship > 0){
sleep(2);
pthread_mutex_lock(&mutex);
result = scholarship * PERCENTAGE;
result = ceil(result);
total = total + result;
scholarship = scholarship - result;
if( result >= 1){
printf("A = ");
printf("%.2f",result);
printf("\n");
}
if( scholarship < 1){
pthread_exit(0);
printf("Thread A exited\n");
return;
}
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void *B(){
float result;
while(scholarship > 0){
sleep(1);
pthread_mutex_lock(&mutex);
result = scholarship * PERCENTAGE;
result = ceil(result);
total = total + result;
scholarship = scholarship - result;
if( result >= 1){
printf("B = ");
printf("%.2f",result);
printf("\n");
}
if( scholarship < 1){
pthread_exit(0);
printf("Thread B exited\n");
return;
}
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void *C(){
float result;
while(scholarship > 0){
sleep(1);
pthread_mutex_lock(&mutex);
result = scholarship * PERCENTAGE;
result = ceil(result);
total = total + result;
scholarship = scholarship - result;
if( result >= 1){
printf("C = ");
printf("%.2f",result);
printf("\n");
}
if( scholarship < 1){
pthread_exit(0);
printf("Thread C exited\n");
return;
}
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void *totalCalc(){
printf("Total given out: ");
printf("%d", total);
printf("\n");
}
输出:
B = 1000.00
C = 750.00
A = 563.00
B = 422.00
C = 317.00
B = 237.00
C = 178.00
A = 134.00
B = 100.00
C = 75.00
B = 56.00
C = 42.00
A = 32.00
B = 24.00
C = 18.00
B = 13.00
C = 10.00
A = 8.00
B = 6.00
C = 4.00
B = 3.00
C = 2.00
A = 2.00
B = 1.00
C = 1.00
B = 1.00
C = 1.00
^C
【问题讨论】:
-
初始化互斥体
pthread_mutex_t mutex;-->pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; -
这些:
void *A(); void *B(); void *C();不是有效的线程函数签名;它们应该是: void *A( void *pData );无效*B(无效*pData);无效 *C( 无效 *pData );` -
没有警告或错误。
-
这种行:
pthread_exit(0);一旦被执行,后面的代码就不会被执行,所以每个线程都有一些无法访问的代码。顺便说一句:那个参数应该是:NULL,而不是0 -
贴出的代码存在逻辑问题。线程在解锁互斥锁之前调用
pthread_exit()
标签: c multithreading pthreads