C 与 多线程(1)
C 与 多线程(1)
我们可以用C编写多线程程序吗?
- C 语言标准不支持多线程
- POSIX Threads (or Pthreads) is a POSIX standard for threads.
- gcc compiler 提供了一种 pthread 的实现
一个简单的C程序来演示pthread基本功能的使用
请注意,下面的程序只能与带有pthread库的C编译器一起编译。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> //Header file for sleep(). man 3 sleep for details.
#include <pthread.h>
// A normal C function that is executed as a thread
// when its name is specified in pthread_create()
void *myThreadFun(void *vargp)
{
sleep(1);
printf("Printing GeeksQuiz from Thread \n");
return NULL;
}
int main()
{
pthread_t thread_id;
printf("Before Thread\n");
pthread_create(&thread_id, NULL, myThreadFun, NULL);
pthread_join(thread_id, NULL);
printf("After Thread\n");
exit(0);
}
编译
要使用gcc编译多线程程序,我们需要将其与pthreads库链接。
gcc multithread.c -lpthread
运行
./a.out
多线程具有全局变量和静态变量
所有线程共享数据段
。全局变量
和静态变量
存储在数据段
中。因此,它们被所有线程共享。下面的示例程序进行了演示。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
// Let us create a global variable to change it in threads
int g = 0;
// The function to be executed by all threads
void *myThreadFun(void *vargp)
{
// Store the value argument passed to this thread
int *myid = (int *)vargp;
// Let us create a static variable to observe its changes
static int s = 0;
// Change static and global variables
++s; ++g;
// Print the argument, static and global variables
printf("Thread ID: %d, Static: %d, Global: %d\n", *myid, ++s, ++g);
}
int main()
{
int i;
pthread_t tid;
// Let us create three threads
for (i = 0; i < 3; i++)
pthread_create(&tid, NULL, myThreadFun, (void *)&tid);
pthread_exit(NULL);
return 0;
}
请注意,以上是显示线程如何工作的简单示例。在线程中访问全局变量通常不是一个好主意
。如果线程2优先于线程1并且线程1需要更改变量,该怎么办。实际上,如果需要多个线程访问全局变量,则应使用互斥锁
对其进行访问。
References:
- http://www.csc.villanova.edu/~mdamian/threads/posixthreads.html
- Computer Systems : A Programmer
原文:
- https://www.geeksforgeeks.org/multithreading-c-2/