第1关:创建线程
通常我们编写的程序都是单进程,如果在一个进程中没有创建新的线程,则这个单进程程序也就是单线程程序。本关我们将介绍如何在一个进程中创建多个线程。
本关任务:学会使用C语言在Linux系统中使用pthread_create库函数创建一个新的线程
#include <stdio.h>
#include <pthread.h>
/************************
* 参数start_routine: 函数指针,用于指向线程函数
* 参数arg: 是线程函数的参数
* 返回值: 返回线程ID
*************************/
pthread_t createThread(void *(*start_routine) (void *), void *arg)
{
pthread_t thread;
/********** BEGIN **********/
int ret = pthread_create(&thread, NULL, start_routine,arg);
/********** END **********/
return thread;
}
第2关:线程挂起
在学习多进程编程的时候,我们学习了如何等待一个进程结束,那么在多线程中也存在同样的操作,如何使得一个线程挂起等待其他的线程先执行。本关我们将介绍如何挂起一个线程,并等待指定线程。
本关任务:学会使用C语言在Linux系统中使用pthread_join库函数挂起当前线程,并等待指定的线程。
#include <stdio.h>
#include <pthread.h>
/************************
* 参数thread: 需要等待结束的线程ID号
* 返回值: 等待成功返回0,失败返回-1
* 提示: 忽略线程返回值
*************************/
int waitThread(pthread_t thread)
{
int ret = -1;
/********** BEGIN **********/
int pthread_join(pthread_t thread, void **waitThread);
if(pthread_join(thread, NULL) != 0)
/********** END **********/
return ret;
}
第3关:线程终止
在学习多进程编程的时候,我们知道进程的退出有很多中方式,常见的有exit函数,而线程的退出也有多种方法。本关我们将介绍如何终止一个线程的执行。
本关任务:学会使用C语言在Linux系统中终止一个线程。
#include <stdio.h>
#include <pthread.h>
/************************
* 参数thread: 需要等待结束的线程ID号
* 返回值: 等待成功返回0,失败返回-1
* 提示: 忽略线程返回值
*************************/
int cancelThread(pthread_t thread)
{
int ret = -1;
/********** BEGIN **********/
ret = pthread_cancel(thread);
/********** END **********/
return ret;
}
本篇博客介绍了如何使用C语言在Linux系统中通过pthread库实现线程创建、线程挂起等待和线程终止的基本操作。通过实例演示了`pthread_create`、`pthread_join`和`pthread_cancel`函数的用法,是初学者理解多线程编程的重要步骤。
845

被折叠的 条评论
为什么被折叠?



