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:
原文:
- https://www.geeksforgeeks.org/multithreading-c-2/