linux进程线程管理实验报告(10)
时间:2025-07-09
时间:2025-07-09
进程线程,死锁实验报告
void* thread_worker(void* p){
int thread_num;
thread_num=(int)p;
for(;;){
main_counter++;
counter[thread_num]++;
}
}
4.2回答上述实验要求中的问题:
1.程序运行会出现中止现象,可能会资源互斥。
2.实际运行时程序会在运行期间中止,出现死锁现象。多次运行之后现象都一样。 解释如下:主线程申请mutex1资源,而子线程申请mutex2资源,此时主线程继续申请mutex2资源,子线程来申请mutex1资源,而mutex2资源还未被子线程释放,主线程无法申请到,同样的,mutex1资源未被主线程释放则子线程也无法申请到,此时便处于无限循环等待,形成死锁。
修改后的程序:
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<ctype.h>
#include<pthread.h>
#define LOOP_TIMES 1000
pthread_mutex_t mutex1=PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2=PTHREAD_MUTEX_INITIALIZER;
void* thread_worker(void *);
void critical_section(int threadd_num,int i);
int main(int argc,char *argv[]){
int rtn,i;
pthread_t pthread_id=0;
rtn=pthread_create(&pthread_id,NULL,thread_worker,NULL);
if(rtn!=0){
printf("pthread_create ERROR!\n");
return -1;
}
for(i=0;i<LOOP_TIMES;i++){
pthread_mutex_lock(&mutex1);
pthread_mutex_lock(&mutex2);
critical_section(1,i);
pthread_mutex_unlock(&mutex2);
pthread_mutex_unlock(&mutex1);
上一篇:数学教案第一周