更新時間:2021-10-09 10:45:11 來源:動力節點 瀏覽1321次
線程是一個執行單元,由其程序計數器、堆棧和一組寄存器組成。人們總是混淆線程和進程,區別很簡單,進程提供執行程序所需的資源,而線程是進程內可以調度執行的實體。線程比進程有很多優點,主要的優點是,線程通過并行改進應用程序。我們將利用這個并行概念來編寫一個簡單的 C 并理解為什么我們需要線程同步。
讓我們編寫一個具有單線程的簡單 C 程序。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
volatile long int a = 0;
int main()
{
int i;
a = 0;
for(i = 0; i < 100000; i++)
{
a = a + i;
}
printf("%ld\n",a);
return 0;
}
上面的代碼很簡單,它是單線程的,不用擔心并行性。當我們執行并運行上面的代碼時,我們每次都會得到4999950000。該代碼具有三個主要的機器代碼指令。
LDR R0, a
ADD R0, R0, R1
STR R0, a
現在讓我們稍微修改一下多線程的代碼,看看它的行為。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
volatile long int a = 0;
pthread_mutex_t aLock;
void threadFunc()
{
int i;
for (i = 1; i < 200000 ; i++)
{
a = a + 1;
}
}
void threadFunc2()
{
int i;
for(i = 200000; i <= 500000; i++)
{
a = a + i;
}
}
int main()
{
pthread_t th_one, th_two;
int i;
a = 0;
pthread_create(&th_one, NULL, (void*)&threadFunc, NULL); // Create a new thread for threadFunc
pthread_create(&th_two, NULL, (void*)&threadFunc2, NULL); // Create a new thread for threadFunc2
pthread_join(th_one, NULL); // waiting to join thread "th_one" without status
pthread_join(th_two, NULL); // waiting to join thread "th_two" without status
printf("%ld\n",a);
return 0;
}
我們創建了兩個新線程threadFunc和threadFunc2。讓我們用命令編譯上面的代碼
$ gcc -pthread m_thread.c -o m_thread
當我們多次運行二進制 m_thread 時,我們會看到類似這樣的內容
令我們驚訝的是,輸出是不確定的。那么,造成這種奇怪現象的原因可能是什么?為什么我的電腦會這樣?答案是,我們沒有處理線程同步。讓我們了解為什么會發生這種情況。
在 SC1 中,'a' 被加載到 th1 的本地內存中,然后它執行操作并存儲回主內存。類似地,在 SC2 中,'a' 被加載到 th2 的本地內存中,并在操作后存儲回主內存。現在,在 SC3 'a' 由 th1 和 th2 獲取,因為沒有線程同步,因此我們可以看到 th1 存儲的值丟失了,操作后基本上由 th2 更新。這是我為我們的理解添加的一個結果。然而,每次我們朗姆酒二進制可執行文件時,后臺都會發生許多這樣的后果,導致不同的輸出。
現在,我們如何實現進程同步?一種方法是使用互斥鎖。請參閱下面的修改示例。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
volatile long int a = 0;
pthread_mutex_t aLock;
void threadFunc(void* arg)
{
int i;
for (i = 1; i < 200000 ; i++)
{
pthread_mutex_lock(&aLock); // Lock a mutex for a
a = a + 1;
pthread_mutex_unlock(&aLock); // Unlock a mutex for a
}
}
void threadFunc2(void *arg)
{
int i;
for(i = 200000; i <= 500000; i++)
{
pthread_mutex_lock(&aLock); // Lock a Mutex for a
a = a + i;
pthread_mutex_unlock(&aLock); // Unlock a mutex for a
}
}
int main()
{
pthread_t th_one, th_two;
int i;
a = 0;
pthread_create(&th_one, NULL, (void*)&threadFunc, NULL); // Create a new thread for threadFunc
pthread_create(&th_two, NULL, (void*)&threadFunc2, NULL); // Create a new thread for threadFunc2
pthread_join(th_one, NULL); // waiting to join thread "one" without status
pthread_join(th_two, NULL); // waiting to join thread "two" without status
printf("%ld\n",a);
return 0;
當我們執行上述二進制文件時,我們每次運行都會得到相同的輸出。
在這種方法中,在代碼的入口部分,在臨界區內修改和使用的關鍵資源上獲取一個 LOCK,并在退出部分釋放 LOCK。由于資源在進程執行其臨界區時被鎖定,因此其他進程無法訪問它。
以上就是多線程同步的例子,大家若想了解更多相關信息,可以關注一下動力節點的Java多線程編程教程,里面有更詳細的知識可以學習,希望對大家能夠有所幫助。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習