Linux 執行緒同步

2021-07-24 18:17:55 字數 2024 閱讀 5464

互斥量用pthread_mutex_t資料型別來表示,在使用互斥變數以前,必須先對其進行初始化,可以將其置為常量pthread_mutex_initializer(只能用於靜態分配的互斥量),也可以呼叫pthread_mutex_init函式進行初始化。若是動態的互斥量(如:呼叫malloc),就要在釋放記憶體前先呼叫pthread_mutex_destroy函式。

#include

int pthread_mutex_init(pthread_mutex_t *restrict mutex,

const pthread_mutexattr_t *restrict attr);   //attr = null時,使用預設屬性初始化互斥量

int pthread_mutex_destroy(pthread_mutex_t *mutex);

#include

int pthread_mutex_lock(pthread_mutex_t *mutex);

int pthread_mutex_trylock(pthread_mutex_t *mutex);

int pthread_mutex_unlock(pthread_mutex_t *mutex);

如果執行緒不希望被阻塞,

//使用互斥鎖保護資料結構

#include #include #include #include #include struct foo

;struct foo *foo_alloc(void)

} return(fp);

}void foo_hold(struct foo *fp)

void foo_rele(struct fpp *fp)

else

}

如果執行緒試圖對同乙個互斥量加鎖兩次,那麼它自身就會陷入死鎖狀態。當

需要同時使用兩個互斥鎖時,總是讓它們以相同的順序加鎖,以避免死鎖,第二個互斥鎖維護著乙個用於跟蹤foo資料結構的雜湊列表。這樣hashlock互斥鎖保護foo資料結構中的fh雜湊表和f_next雜湊鍊子段。foo結構中的f_lock互斥鎖保護對foo結構中的其他欄位的訪問。

//使用兩個互斥鎖

#include #include #define nhash 29

#define hash(fp) (((unsigned long)fp) %nhash)

struct foo *fh[nhash];

pthread_muxtex_t hashlock = pthread_mutex_initializer;

struct foo

;struct foo *foo_alloc(void)

idx = hash(fp);

pthread_mutex_lock(&hashlock);

fp->f_next = fh[idx];

fh[idx] = fp->f_next;

pthread_mutex_lock(&fp->f_lock);

pthread_mutex_unlock(&hashlock);

pthread_mutex_unlock(&fp->f_lock);

} rerutn(fp);

}struct foo *foo_find(int id)

} pthread_mutex_unlock(&hashlock);

return(fp);

}void foo_rele(struct foo *fp)

idx = hash(fp);

tfp = fh[idx];

if(tfp == fp)

else

tfp->f_next = fp->f_next;

} pthread_mutex_unlock(&hashlock);

pthread_mutex_unlock(&fp->f_lock);

pthread_mutex_destroy(&fp->f_lock);

free(fp);

} else

}

linux 執行緒 執行緒同步

因為執行緒獨自擁有的只有棧,其他的區域執行緒共同擁有。並且對共享區域的操作並不都是原子的。對共享區域的操作順序又是不確定的。就像建立兩個檔案描述符同時指向 同一檔案,並且連續向檔案中寫入那麼寫的東西可能是亂七八糟的。這時就需要執行緒對共享區的同步。而另一種情況是,多個執行緒的指令執行順序需要同步。這...

Linux執行緒同步

1.概要 執行緒的同步,發生在多個執行緒共享相同記憶體的時候,這時,要保證每個執行緒在每個時刻看到的共享資料是一致的。如果每個執行緒使用的變數都是其他執行緒不會使用的 read write 或者變數是唯讀的,就不存在一致性問題。但是,如果兩個或兩個以上的執行緒可以read write乙個變數時,就需...

Linux執行緒同步

1.概要 執行緒的同步,發生在多個執行緒共享相同記憶體的時候,這時,要保證每個執行緒在每個時刻看到的共享資料是一致的。如果每個執行緒使用的變數都是其他執行緒不會使用的 read write 或者變數是唯讀的,就不存在一致性問題。但是,如果兩個或兩個以上的執行緒可以read write乙個變數時,就需...