long AtomicCompareExchange(long* atomicvar, long compared, long exchange)
return InterlockedCompareExchange(atomicvar, exchange, compared);
//long AtomicExchange(long* atomicvar,long exchange)
// return InterlockedExchange(atomicvar, exchange);
void PLC_GetTime(IEC_TIME *CURRENT_TIME)
(*CURRENT_TIME).tv_sec = timetmp.time;
(*CURRENT_TIME).tv_nsec = timetmp.millitm * 1000000;
PLC_GetTime(&__CURRENT_TIME);
void PLC_SetTimer(long long next, long long period)
/* arg 2 of SetWaitableTimer take 100 ns interval*/
liDueTime.QuadPart = next / (-100);
printf("SetTimer(%lld,%lld)\n",next, period);
if (!SetWaitableTimer(PLC_timer, &liDueTime, common_ticktime__, NULL, NULL, 0))
printf("SetWaitableTimer failed (%d)\n", GetLastError());
/* Variable used to stop plcloop thread */
PLC_SetTimer(Ttick,Ttick);
if (WaitForSingleObject(PLC_timer, INFINITE) != WAIT_OBJECT_0)
printf("WaitForSingleObject failed (%d)\n", GetLastError());
int startPLC(int argc,char **argv)
unsigned long thread_id = 0;
/* Translate PLC's microseconds to Ttick nanoseconds */
Ttick = 1000000 * maxval(common_ticktime__,1);
debug_sem = CreateSemaphore(
NULL, // default security attributes
MAX_SEM_COUNT, // maximum count
NULL); // unnamed semaphore
printf("CreateMutex error: %d\n", GetLastError());
wait_sem = CreateSemaphore(
NULL, // default security attributes
MAX_SEM_COUNT, // maximum count
NULL); // unnamed semaphore
printf("CreateMutex error: %d\n", GetLastError());
/* Create a waitable timer */
PLC_timer = CreateWaitableTimer(NULL, FALSE, "WaitableTimer");
printf("CreateWaitableTimer failed (%d)\n", GetLastError());
if( __init(argc,argv) == 0 )
printf("Tick Time : %d ms\n", common_ticktime__);
PLC_thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)PlcLoop, NULL, 0, &thread_id);
int TryEnterDebugSection(void)
//printf("TryEnterDebugSection\n");
return WaitForSingleObject(debug_sem, 0) == WAIT_OBJECT_0;
void LeaveDebugSection(void)
ReleaseSemaphore(debug_sem, 1, NULL);
//printf("LeaveDebugSection\n");
WaitForSingleObject(PLC_thread, INFINITE);
ReleaseSemaphore(wait_sem, 1, NULL);
/* from plc_debugger.c */
WaitForSingleObject(wait_sem, INFINITE);
/* Called by PLC thread when debug_publish finished
* This is supposed to unlock debugger thread in WaitDebugData*/
void InitiateDebugTransfer()
/* Leave debugger section */
ReleaseSemaphore(debug_sem, 1, NULL);
/* signal debugger thread it can read data */
ReleaseSemaphore(wait_sem, 1, NULL);
/* Prevent PLC to enter debug code */
WaitForSingleObject(debug_sem, INFINITE);
/* Let PLC enter debug code */
ReleaseSemaphore(debug_sem, 1, NULL);