在Linux中,多线程编程是一种强大的技术,可以创建并发应用程序。使用多线程,我们可以在一个进程中同时执行多个任务,从而提高效率和响应能力。以下是一些Linux中多线程编程的优秀代码示例:
创建线程
在Linux中,我们可以使用以下代码创建线程:
int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_routine)(void *), void *restrict arg);
其中:
* tidp :线程ID
* attr :线程属性
* start_routine :线程执行函数
* arg :传给线程执行函数的参数
线程同步
为了确保多个线程安全地同时访问共享资源,需要使用同步机制。在Linux中,可以使用以下代码实现线程同步:
互斥锁
互斥锁用于确保一次只有一个线程可以访问共享资源。
int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr);
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);
信号量
信号量用于控制共享资源的访问次数。
int sem_init(sem_t *sem, int pshared, unsigned int value);
int sem_wait(sem_t *sem);
int sem_post(sem_t *sem);
线程终止
当线程完成执行时,需要终止它。我们可以使用以下代码终止线程:
int pthread_exit(void *retval);
其中, retval 是线程返回的值。
示例代码
以下是一个简单的多线程编程示例:
include
include
void *thread_function(void *arg)
{
printf("Hello from thread %d\n", (int)arg);
return NULL;
}
int main()
{
pthread_t threads[5];
for (int i = 0; i < 5; i++)
{
pthread_create(&threads[i], NULL, thread_function, (void *)i);
}
for (int i = 0; i < 5; i++)
{
pthread_join(threads[i], NULL);
}
return 0;
}
这个程序创建了5个线程,每个线程打印一个消息。使用 pthread_create 创建线程,使用 pthread_join 等待线程完成执行。