C语言多线程编程实例
多线程编程是一种并发编程的方式,它可以让程序同时执行多个任务,提高程序的效率和响应速度。C语言是一种广泛使用的编程语言,也支持多线程编程。本文将介绍一些C语言多线程编程的实例,帮助读者更好地理解和掌握多线程编程技术。 1. 创建线程
在C语言中,可以使用pthread库来创建线程。下面是一个简单的例子,创建一个线程并让它输出一段文字:
```
#include <stdio.h>
#include <pthread.h>
void* thread_func(void* arg)
{
printf("Hello, world!\n");
return NULL;
}
int main()
浙江树人大学后勤
{
pthread_t tid;
pthread_create(&tid, NULL, thread_func, NULL);
pthread_join(tid, NULL);
return 0;
}
```
在上面的代码中,我们定义了一个函数thread_func,它将作为线程的入口函数。在main函数中,我们使用pthread_create函数创建了一个线程,并将thread_func作为入口函数。然后使用pthread_join函数等待线程结束。 2. 线程同步
在多线程编程中,线程之间的同步非常重要。下面是一个例子,演示如何使用互斥锁来保护共享资源:
品质因数q```
#include <stdio.h>
#include <pthread.h>动力基因论坛
int count = 0;
pthread_mutex_t mutex;
void* thread_func(void* arg)
{
pthread_mutex_lock(&mutex);
count++;
printf("Thread %d: count = %d\n", (int)arg, count);
pthread_mutex_unlock(&mutex);
return NULL;
}
int main()
{
pthread_t tid1, tid2;
pthread_mutex_init(&mutex, NULL);
国家燃烧 pthread_create(&tid1, NULL, thread_func, (void*)1);
pthread_create(&tid2, NULL, thread_func, (void*)2);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
pthread_mutex_destroy(&mutex);
return 0;
}
```
在上面的代码中,我们定义了一个全局变量count,它将被两个线程同时访问。为了保护count,我们使用了互斥锁mutex。在每个线程中,我们先使用pthread_mutex_lock函数锁
定互斥锁,然后对count进行操作,最后使用pthread_mutex_unlock函数释放互斥锁。
3. 条件变量
条件变量是一种线程同步的机制,它可以让线程等待某个条件的发生。下面是一个例子,演示如何使用条件变量来实现生产者-消费者模型:
```
#include <stdio.h>
#include <pthread.h>
#define BUFFER_SIZE 10
int buffer[BUFFER_SIZE];
焊后热处理int count = 0;
pthread_mutex_t mutex;
pthread_cond_t cond;
void* producer_func(void* arg)
{
int i;
for (i = 0; i < 100; i++) {
pthread_mutex_lock(&mutex);
青岛大炼油