多任务互斥与同步(互斥锁, 读写锁, 条件变量, 信号量, 命名信号量): 作业3
This commit is contained in:
		
							parent
							
								
									0df47fc15c
								
							
						
					
					
						commit
						663a501a63
					
				
							
								
								
									
										42
									
								
								day7/homework/h3.c
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										42
									
								
								day7/homework/h3.c
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,42 @@ | ||||
| /*
 | ||||
| 编写一个程序, 创建多个线程, 每个线程负责对一个共享计数器进行自增操作。要求实现线程间的互斥, 确保每个线程对计数器的自增操作是原子的, 不会出现竞争条件。 | ||||
| */ | ||||
| #include <stdio.h> | ||||
| #include <pthread.h> | ||||
| #include <unistd.h> | ||||
| #include <semaphore.h> | ||||
| 
 | ||||
| sem_t sem; | ||||
| int number = 0; | ||||
| 
 | ||||
| void * | ||||
| addfun(void *data) | ||||
| { | ||||
|     sem_wait(&sem); | ||||
|     number++; | ||||
|     printf("%ld 线程时, number = %d\n", pthread_self(), number); | ||||
|     sem_post(&sem); | ||||
| } | ||||
| 
 | ||||
| int main(int argc, char const *argv[]) | ||||
| { | ||||
|     sem_init(&sem, 0, 1); | ||||
|     printf("开始的 number = %d\n", number); | ||||
| 
 | ||||
|     pthread_t t[5]; | ||||
|     for (int i = 0; i < 5; i++) | ||||
|     { | ||||
|         pthread_create(&t[i], NULL, addfun, NULL); | ||||
|     } | ||||
| 
 | ||||
|     for (int i = 0; i < 5; i++) | ||||
|     { | ||||
|         pthread_join(t[i], NULL); | ||||
|     } | ||||
| 
 | ||||
|     printf("现在的 number = %d\n", number); | ||||
| 
 | ||||
|     sem_destroy(&sem); | ||||
| 
 | ||||
|     return 0; | ||||
| } | ||||
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user