写一个使用C语言的模拟进程间的创建、终止、阻塞、唤醒的代码
时间: 2023-10-18 16:06:24 浏览: 146
好的,以下是一个简单的模拟进程间的创建、终止、阻塞、唤醒的代码,供您参考:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#define MAX_THREADS 10
pthread_t threads[MAX_THREADS];
int thread_status[MAX_THREADS];
void *thread_func(void *arg) {
int id = *(int *)arg;
printf("Thread %d started\n", id);
while (1) {
if (thread_status[id] == 0) {
printf("Thread %d blocked\n", id);
sleep(1);
} else if (thread_status[id] == 1) {
printf("Thread %d running\n", id);
sleep(1);
} else if (thread_status[id] == 2) {
printf("Thread %d terminated\n", id);
break;
}
}
return NULL;
}
int create_thread() {
int i;
for (i = 0; i < MAX_THREADS; i++) {
if (thread_status[i] == -1) {
thread_status[i] = 0;
int *id = malloc(sizeof(int));
*id = i;
pthread_create(&threads[i], NULL, thread_func, id);
return i;
}
}
return -1;
}
void terminate_thread(int id) {
thread_status[id] = 2;
}
void block_thread(int id) {
thread_status[id] = 0;
}
void unblock_thread(int id) {
thread_status[id] = 1;
}
int main() {
int i, j;
for (i = 0; i < MAX_THREADS; i++) {
thread_status[i] = -1;
}
for (i = 0; i < 5; i++) {
create_thread();
}
for (i = 0; i < 10; i++) {
for (j = 0; j < MAX_THREADS; j++) {
if (thread_status[j] == 1) {
printf("Unblocking thread %d\n", j);
unblock_thread(j);
break;
}
}
sleep(1);
for (j = 0; j < MAX_THREADS; j++) {
if (thread_status[j] == 0) {
printf("Blocking thread %d\n", j);
block_thread(j);
}
}
}
for (i = 0; i < MAX_THREADS; i++) {
if (thread_status[i] != -1) {
terminate_thread(i);
pthread_join(threads[i], NULL);
}
}
return 0;
}
```
这个代码使用了 pthread 库来创建线程,每个线程都有一个状态,可以是阻塞、运行或终止。主线程会不断地轮流唤醒和阻塞线程,直到所有线程都终止。
阅读全文