您的位置:首页 > 其它

信号量、Windows事件实现线程同步

2016-03-25 01:12 393 查看
#include <stdio.h>
#include <Windows.h>
#include <process.h>

using namespace std;

HANDLE sem_add, sem_subtract;

int val(0);

unsigned int __stdcall add(void* lpa)
{
printf("add\n");
while (true)
{
WaitForSingleObject(sem_add, INFINITE);
++val;
printf("add: %d\n", val);
ReleaseSemaphore(sem_subtract, 1, NULL);
}

//return 999;
}

unsigned int __stdcall subtract(void* lpa)
{
printf("subtract\n");
while (true)
{
WaitForSingleObject(sem_subtract, INFINITE);
--val;
printf("subtract: %d\n", val);
ReleaseSemaphore(sem_add, 1, NULL);
}

//return 999;
}

int main(int argc, char ** argv)
{
sem_add = CreateSemaphore(NULL, 1, 10, NULL);

sem_subtract = CreateSemaphore(NULL, 0, 10, NULL);

//ReleaseSemaphore();
printf("[%d]: sem init 0\n", __LINE__);

HANDLE hThr;
hThr = (HANDLE)_beginthreadex(NULL, 0, add, NULL, 0, NULL);

HANDLE hThr2;
hThr2 = (HANDLE)_beginthreadex(NULL, 0, subtract, NULL, 0, NULL);

WaitForSingleObject(hThr, INFINITE);
WaitForSingleObject(hThr2, INFINITE);

return 0;
}


#include <stdio.h>
#include <semaphore.h>
#include <pthread.h>

using namespace std;

int val(0);

sem_t sem_add, sem_subtract;

void * addFun(void * arg)
{
while(true)
{
sem_wait(&sem_add);
++val;
printf("addFun: %d\n", val);
sem_post(&sem_subtract);
}
}

void * subtractFun(void * arg)
{
while(true)
{
sem_wait(&sem_subtract);
--val;
printf("subtractFun: %d\n", val);
sem_post(&sem_add);
}
}

int main(int argc, char **argv)
{
int ret(0);
sem_init(&sem_add, 0, 10);
sem_init(&sem_subtract, 0, 0);
//    printf("[%d]: %d\n", __LINE__, sem_val);

pthread_t t_id;
ret = pthread_create(&t_id, NULL, addFun, NULL);

pthread_t t_id2;
ret = pthread_create(&t_id2, NULL, subtractFun, NULL);

pthread_join(t_id, NULL);
pthread_join(t_id2, NULL);

return 0;
}


#include <stdio.h>
#include <Windows.h>
#include <process.h>

using namespace std;

//HANDLE sem_add, sem_subtract;
HANDLE eve_add, eve_subtract;

int val(0);

unsigned int __stdcall add(void* lpa)
{
printf("add\n");
while (true)
{
WaitForSingleObject(eve_add, INFINITE);
//ResetEvent(eve_add);
++val;
printf("add: %d\n", val);
SetEvent(eve_subtract);
}
}

unsigned int __stdcall subtract(void* lpa)
{
printf("subtract\n");
while (true)
{
WaitForSingleObject(eve_subtract, INFINITE);
//ResetEvent(eve_subtract);
--val;
printf("subtract: %d\n", val);
SetEvent(eve_add);
}
}

int main(int argc, char ** argv)
{
eve_add = CreateEvent(NULL, false, TRUE, NULL);

eve_subtract = CreateEvent(NULL, false, FALSE, NULL);

printf("[%d]: sem init 0\n", __LINE__);

HANDLE hThr;
hThr = (HANDLE)_beginthreadex(NULL, 0, add, NULL, 0, NULL);

HANDLE hThr2;
hThr2 = (HANDLE)_beginthreadex(NULL, 0, subtract, NULL, 0, NULL);

WaitForSingleObject(hThr, INFINITE);
WaitForSingleObject(hThr2, INFINITE);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: