1、linux下,用gcc編譯c代碼,error:undefined reference to sem_wait 怎麼解決?謝謝! 請問 在哪兒找到的
#include <semaphore.h>
int sem_wait(sem_t *sem);
int sem_trywait(sem_t *sem);
int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout);
Link with -lrt or -pthread.
自己看最後一句....手冊裡面寫著呢....link with -lrt or -pthread
2、怎麼用c語言編程 實現創建原語、撤銷原語、阻塞原語和喚醒原語
下,應該差不多
一、如何建立線程
用到的頭文件
(a)pthread.h
(b)semaphore.h
(c) stdio.h
(d)string.h
定義線程標識
pthread_t
創建線程
pthread_create
對應了一個函數作為線程的程序段
注意的問題
要保證進程不結束(在創建線程後加死循環)
在線程中加入While(1)語句,也就是死循環,保證進程不結束。
二、控制線程並發的函數
sem_t:信號量的類型
sem_init:初始化信號量
sem_wait:相當於P操作
sem_post:相當於V操作
三、實現原形系統
父親、母親、兒子和女兒的題目:
桌上有一隻盤子,每次只能放入一隻水果。爸爸專放蘋果,媽媽專放橘子,一個兒子專等吃盤子中的橘子,一個女兒專等吃盤子中的蘋果。分別用P,V操作和管程實現
每個對應一個線程
pthread_t father; father進程
pthread_t mother; mother進程
pthread_t son; son進程
pthread_t daughter; daughter進程
盤子可以用一個變數表示
sem_t empty;
各線程不是只做一次,可以是無限或有限次循環
用While(1)控制各線程無限次循環
輸出每次是那個線程執行的信息
printf("%s\n",(char *)arg);通過參數arg輸出對應線程執行信息
編譯方法
gcc hex.c -lpthread
生成默認的可執行文件a.out
輸入./a.out命令運行
查看結果:程序連續運行顯示出
father input an apple.
daughter get an apple.
mother input an orange.
son get an orange.
mother input an orange.
son get an orange.
………………..
四、程序源代碼
#include <stdio.h>
#include<string.h>
#include <semaphore.h>
#include <pthread.h>
sem_t empty; //定義信號量
sem_t applefull;
sem_t orangefull;
void *procf(void *arg) //father線程
{
while(1){
sem_wait(&empty); //P操作
printf("%s\n",(char *)arg);
sem_post(&applefull); //V操作
sleep(7);
}
}
void *procm(void *arg) //mother線程
{
while(1){
sem_wait(&empty);
printf("%s\n",(char *)arg);
sem_post(&orangefull);
sleep(3);
}
}
void *procs(void *arg) //son線程
{
while(1){
sem_wait(&orangefull);
printf("%s\n",(char *)arg);
sem_post(&empty);
sleep(2);
}
}
void *procd(void *arg) //daughter線程
{
while(1){
sem_wait(&applefull);
printf("%s\n",(char *)arg);
sem_post(&empty);
sleep(5);
}
}
main()
{
pthread_t father; //定義線程
pthread_t mother;
pthread_t son;
pthread_t daughter;
sem_init(&empty, 0, 1); //信號量初始化
sem_init(&applefull, 0, 0);
sem_init(&orangefull, 0, 0);
pthread_create(&father,NULL,procf,"father input an apple."); //創建線程
pthread_create(&mother,NULL,procm,"mother input an orange.");
pthread_create(&daughter,NULL,procd,"daughter get an apple.");
pthread_create(&son,NULL,procs,"son get an orange.");
while(1){} //循環等待
}
另外,站長團上有產品團購,便宜有保證
3、急!LINUX下,GCC編譯,原程序包含<semaphore.h>頭文件,為什麼編譯時說sem_wait,sem_post等未定義的引用
編譯時加上參數:-lpthread
要看報錯的階段,是在編譯還是鏈接階段.
如果編譯時函數沒有找到,那是頭文件的問題,如果鏈接時未定義引用,那是c庫的問題.
如果你的頭文件都正常包含了,那可能你的c庫沒有使能semaphore的支持.