这个案例里面 信号服务器这边必须先启动。服务端代码:
#include <fcntl.h> /* For O_* constants */
#include <sys/stat.h> /* For mode constants */
#include <semaphore.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/mman.h>
#define SEM_NAME "MY_SEM_NAME"
bool bExitThread = false;
sem_t *g_sem;
pthread_t g_thread1;
void* process(void* args)
{
int* p = (int*)args;
while(true){
if(bExitThread){
break;
}
sem_post(g_sem);//通知线程信号量已经置位
usleep(2000 * 1000);
}
delete p;
}
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
g_sem = sem_open(SEM_NAME, O_CREAT | O_EXCL, 0644, 0/*important*/);
if(errno == EEXIST){//if semaphore exists, delete semaphore from kernel
sem_unlink(SEM_NAME);//delete semaphore
g_sem = sem_open(SEM_NAME, O_CREAT | O_EXCL, 0644, 0);//create semaphore
}
int val = 0;
sem_getvalue(g_sem, &val);//test semaphore status
int *Args1 = new int(1);
pthread_create(&g_thread1, NULL, process, Args1);//create a thread
}
MainWindow::~MainWindow()
{
bExitThread = true;
pthread_join(g_thread1, NULL);//wait thread exit
sem_close(g_sem);//close semaphore
sem_unlink(SEM_NAME);//delete semaphore from kernel
delete ui;
}
客户端代码:
#include <fcntl.h> /* For O_* constants */
#include <sys/stat.h> /* For mode constants */
#include <semaphore.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/mman.h>
#define SEM_NAME "MY_SEM_NAME"
bool bExitThread = false;
sem_t *g_sem;
pthread_t g_thread1;
unsigned char *pData = NULL;
void* process(void* args)
{
int* p = (int*)args;
while(true){
if(bExitThread){
break;
}
sem_wait(g_sem);//wait signal
usleep(1000 * 1000);
}
delete p;
}
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
g_sem = sem_open(SEM_NAME, O_CREAT, 0644, 0/*初始化为无信号*/);
int val = 0;
sem_getvalue(g_sem, &val);//test semaphore status
int *Args1 = new int(1);
pthread_create(&g_thread1, NULL, process, Args1);//create a thread
}
MainWindow::~MainWindow()
{
bExitThread = true;
pthread_join(g_thread1, NULL);
sem_close(g_sem);
sem_unlink(SEM_NAME);
delete ui;
}
客户端如果没有信号不会进入usleep函数,如果服务端发送信号了,则信号减1,再次等待