用C语言实现四个线程分别打印1,2,3,4
时间: 2023-05-12 14:02:53 浏览: 71
非常感谢您的提问!以下是用 C 语言实现四个线程分别打印 1,2,3,4 的代码:
```c
#include <stdio.h>
#include <pthread.h>
void *print_num(void *arg) {
int num = *(int *)arg;
printf("%d\n", num);
pthread_exit(NULL);
}
int main() {
pthread_t threads[4];
int nums[4] = {1, 2, 3, 4};
for (int i = 0; i < 4; i++) {
pthread_create(&threads[i], NULL, print_num, &nums[i]);
}
for (int i = 0; i < 4; i++) {
pthread_join(threads[i], NULL);
}
return 0;
}
```
希望这个代码对您有所帮助!
相关问题
用C语言实现两个线程,并互相切换
好的,我可以回答这个问题。
使用 C 语言实现两个线程,可以采用 pthread 库来实现。具体步骤如下:
1. 引入 pthread 库:在程序开头加上 #include <pthread.h>
2. 定义线程函数:使用 void* 函数名(void* 参数) 的格式,参数为 void* 类型,线程函数可以执行需要的操作。
3. 创建线程:使用 pthread_create 函数创建线程,该函数的参数包括线程 ID、线程属性和线程函数等。
4. 等待线程结束:使用 pthread_join 函数等待线程结束,参数为线程 ID 和线程返回值。
同时切换两个线程,可以使用互斥锁来实现线程同步。在一个线程中,通过 pthread_mutex_lock 函数锁定互斥锁,执行需要的操作,然后通过 pthread_mutex_unlock 函数解锁互斥锁,使得另一个线程可以获得互斥锁,执行相应操作。
C语言三个线程循环打印ABC
在C语言中,可以使用`pthread`库来实现多线程。具体代码如下:
```c
#include <stdio.h>
#include <pthread.h>
pthread_mutex_t a_lock, b_lock, c_lock;
void* print_thread(void* arg) {
int id = *(int*)arg;
int i;
for (i = 0; i < 5; i++) {
if (id == 0) {
pthread_mutex_lock(&c_lock);
printf("A");
pthread_mutex_unlock(&a_lock);
} else if (id == 1) {
pthread_mutex_lock(&a_lock);
printf("B");
pthread_mutex_unlock(&b_lock);
} else {
pthread_mutex_lock(&b_lock);
printf("C");
pthread_mutex_unlock(&c_lock);
}
}
pthread_exit(NULL);
}
int main() {
pthread_t threads[3];
int ids[3] = {0, 1, 2};
pthread_mutex_init(&a_lock, NULL);
pthread_mutex_init(&b_lock, NULL);
pthread_mutex_init(&c_lock, NULL);
pthread_mutex_lock(&a_lock);
pthread_mutex_lock(&b_lock);
pthread_create(&threads[0], NULL, print_thread, &ids[0]);
pthread_create(&threads[1], NULL, print_thread, &ids[1]);
pthread_create(&threads[2], NULL, print_thread, &ids[2]);
pthread_join(threads[0], NULL);
pthread_join(threads[1], NULL);
pthread_join(threads[2], NULL);
pthread_mutex_destroy(&a_lock);
pthread_mutex_destroy(&b_lock);
pthread_mutex_destroy(&c_lock);
return 0;
}
```
其中,定义了一个`print_thread`函数,用于执行打印操作。每个线程需要持有前一个线程的锁和自己的锁,当前一个线程执行完后,释放前一个锁,再获取自己的锁,进行打印操作。最后,主线程等待所有线程执行完毕后,销毁锁并退出程序。