用C三步实现多线程

看到一篇使用C多线程的好文,于是get这个新技能,顺便把我学到的要点写下来,大家一起分享。英文原文链接:pthreads-in-c-a-minimal-working-example

在C里实现多线程,最简单的方法就是使用Pthreads,使用它的时候线程之间会共享内存和代码。而对于被调用的函数,则相当于同时调用多次(函数内定义的变量不共享)。下面开始快速入门:

第一步:声明和定义

  • 首先在文件头包含Pthreads库:
#include
  • 定义指向这些线程的变量,变量类型为pthread_t,若定义多个可以使用数组或者指针(使用指针记得分配内存)
 pthread_t thread0
  • 定义要使用线程的函数。这个函数的参数返回(void *)类型参数,并且有一个(void *)类型的变量,在这里我们假设这个函数为void *my_entry_function(void *param);

第二步:创建线程并合并

  • 定义完成之后,线程使用pthread_create函数创建并进入指定函数。这个函数有4个参数,第一个为要创建的线程变量的引用,第二个为属性(我们通常使用NULL),第三个为线程要执行的函数,就是上面我们定义的那个,第四个为传入的参数。我们调用的代码长这样:
 pthread_create(&thread0, NULL, my_entry_function, ¶meter)
  • 当线程执行完指定的函数之后,他们的返回值需要合并,这个时候我们调用join_thread函数。这个函数的第一个参数为我们定义的线程变量,第二个参数为指向返回值的指针(没有的话我们用NULL)
 pthread_join(thread0, NULL);

第三部:带参数的编译
最后一步,这一步至关重要,在编译的时候必须加上参数-lpthread :

gcc program.c -o program -lpthread

示例代码如下,我们可以猜猜输出什么:

#include 
#include 

/* this function is run by the second thread */
void *inc_x(void *x_void_ptr)
{

/* increment x to 100 */
int *x_ptr = (int *)x_void_ptr;
while(++(*x_ptr) < 100);

printf("x increment finished\n");

/* the function must return something - NULL will do */
return NULL;

}

int main()
{

int x = 0, y = 0;

/* show the initial values of x and y */
printf("x: %d, y: %d\n", x, y);

/* this variable is our reference to the second thread */
pthread_t inc_x_thread;

/* create a second thread which executes inc_x(&x) */
if(pthread_create(&inc_x_thread, NULL, inc_x, &x)) {

fprintf(stderr, "Error creating thread\n");
return 1;

}
/* increment y to 100 in the first thread */
while(++y < 100);

printf("y increment finished\n");

/* wait for the second thread to finish */
if(pthread_join(inc_x_thread, NULL)) {

fprintf(stderr, "Error joining thread\n");
return 2;

}

/* show the results - x is now 100 thanks to the second thread */
printf("x: %d, y: %d\n", x, y);

return 0;

}

output:
x: 0, y:0
y increment finished
x increment finished
x: 100, y: 100

你可能感兴趣的:(C-C++)