libcm is a C development framework with an emphasis on audio signal processing applications.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

cmThread.c 44KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888
  1. //| Copyright: (C) 2009-2020 Kevin Larke <contact AT larke DOT org>
  2. //| License: GNU GPL version 3.0 or above. See the accompanying LICENSE file.
  3. #include "cmPrefix.h"
  4. #include "cmGlobal.h"
  5. #include "cmRpt.h"
  6. #include "cmErr.h"
  7. #include "cmMem.h"
  8. #include "cmMallocDebug.h"
  9. #include "cmThread.h"
  10. #include <pthread.h>
  11. #include <unistd.h> // usleep
  12. #ifdef OS_OSX
  13. #include <libkern/OSAtomic.h>
  14. #endif
  15. cmThreadH_t cmThreadNullHandle = {NULL};
  16. enum
  17. {
  18. kDoExitThFl = 0x01,
  19. kDoPauseThFl = 0x02,
  20. kDoRunThFl = 0x04
  21. };
  22. typedef struct
  23. {
  24. cmErr_t err;
  25. cmThreadFunc_t funcPtr;
  26. pthread_t pthreadH;
  27. cmThStateId_t state;
  28. void* funcParam;
  29. unsigned doFlags;
  30. unsigned pauseMicroSecs;
  31. unsigned waitMicroSecs;
  32. } cmThThread_t;
  33. cmThRC_t _cmThError( cmErr_t* err, cmThRC_t rc, int sysErr, const char* fmt, ... )
  34. {
  35. va_list vl;
  36. va_start(vl,fmt);
  37. cmErrVSysMsg(err,rc,sysErr,fmt,vl);
  38. va_end(vl);
  39. return rc;
  40. }
  41. void _cmThThreadCleanUpCallback(void* t)
  42. {
  43. ((cmThThread_t*)t)->state = kExitedThId;
  44. }
  45. void* _cmThThreadCallback(void* param)
  46. {
  47. cmThThread_t* t = (cmThThread_t*)param;
  48. // set a clean up handler - this will be called when the
  49. // thread terminates unexpectedly or pthread_cleanup_pop() is called.
  50. pthread_cleanup_push(_cmThThreadCleanUpCallback,t);
  51. while( cmIsFlag(t->doFlags,kDoExitThFl) == false )
  52. {
  53. if( t->state == kPausedThId )
  54. {
  55. cmSleepUs( t->pauseMicroSecs );
  56. if( cmIsFlag(t->doFlags,kDoRunThFl) )
  57. {
  58. t->doFlags = cmClrFlag(t->doFlags,kDoRunThFl);
  59. t->state = kRunningThId;
  60. }
  61. }
  62. else
  63. {
  64. if( t->funcPtr(t->funcParam)==false )
  65. break;
  66. if( cmIsFlag(t->doFlags,kDoPauseThFl) )
  67. {
  68. t->doFlags = cmClrFlag(t->doFlags,kDoPauseThFl);
  69. t->state = kPausedThId;
  70. }
  71. }
  72. }
  73. pthread_cleanup_pop(1);
  74. pthread_exit(NULL);
  75. return t;
  76. }
  77. cmThThread_t* _cmThThreadFromHandle( cmThreadH_t h )
  78. {
  79. cmThThread_t* tp = (cmThThread_t*)h.h;
  80. assert(tp != NULL);
  81. return tp->state==kNotInitThId ? NULL : tp;
  82. }
  83. cmThRC_t _cmThWaitForState( cmThThread_t* t, unsigned stateId )
  84. {
  85. unsigned waitTimeMicroSecs = 0;
  86. while( t->state != stateId && waitTimeMicroSecs < t->waitMicroSecs )
  87. {
  88. //cmSleepUs( t->waitMicroSecs );
  89. cmSleepUs( 15000 );
  90. waitTimeMicroSecs += 15000; //t->waitMicroSecs;
  91. }
  92. return t->state==stateId ? kOkThRC : kTimeOutThRC;
  93. }
  94. cmThRC_t cmThreadCreate( cmThreadH_t* hPtr, cmThreadFunc_t funcPtr, void* funcParam, cmRpt_t* rpt )
  95. {
  96. //pthread_attr_t attr;
  97. cmThRC_t rc = kOkThRC;
  98. cmThThread_t* tp = cmMemAllocZ( cmThThread_t, 1 );
  99. int sysErr;
  100. cmErrSetup(&tp->err,rpt,"Thread");
  101. tp->funcPtr = funcPtr;
  102. tp->funcParam = funcParam;
  103. tp->state = kPausedThId;
  104. tp->doFlags = 0;
  105. tp->pauseMicroSecs = 50000;
  106. tp->waitMicroSecs = 1000000;
  107. if((sysErr = pthread_create(&tp->pthreadH,NULL,_cmThThreadCallback, (void*)tp )) != 0 )
  108. {
  109. tp->state = kNotInitThId;
  110. rc = _cmThError(&tp->err,kCreateFailThRC,sysErr,"Thread create failed.");
  111. }
  112. hPtr->h = tp;
  113. return rc;
  114. }
  115. cmThRC_t cmThreadDestroy( cmThreadH_t* hPtr )
  116. {
  117. cmThRC_t rc = kOkThRC;
  118. if( hPtr==NULL || cmThreadIsValid(*hPtr)==false )
  119. return rc;
  120. cmThThread_t* t = _cmThThreadFromHandle(*hPtr );
  121. if( t == NULL )
  122. return kInvalidHandleThRC;
  123. // tell the thread to exit
  124. t->doFlags = cmSetFlag(t->doFlags,kDoExitThFl);
  125. // wait for the thread to exit and then deallocate the thread object
  126. if((rc = _cmThWaitForState(t,kExitedThId)) == kOkThRC )
  127. {
  128. cmMemFree(t);
  129. hPtr->h = NULL;
  130. }
  131. else
  132. {
  133. rc = _cmThError(&t->err,rc,0,"Thread timed out waiting for destroy.");
  134. }
  135. return rc;
  136. }
  137. cmThRC_t cmThreadPause( cmThreadH_t h, unsigned cmdFlags )
  138. {
  139. cmThRC_t rc = kOkThRC;
  140. bool pauseFl = cmIsFlag(cmdFlags,kPauseThFl);
  141. bool waitFl = cmIsFlag(cmdFlags,kWaitThFl);
  142. cmThThread_t* t = _cmThThreadFromHandle(h);
  143. unsigned waitId;
  144. if( t == NULL )
  145. return kInvalidHandleThRC;
  146. bool isPausedFl = t->state == kPausedThId;
  147. if( isPausedFl == pauseFl )
  148. return kOkThRC;
  149. if( pauseFl )
  150. {
  151. t->doFlags = cmSetFlag(t->doFlags,kDoPauseThFl);
  152. waitId = kPausedThId;
  153. }
  154. else
  155. {
  156. t->doFlags = cmSetFlag(t->doFlags,kDoRunThFl);
  157. waitId = kRunningThId;
  158. }
  159. if( waitFl )
  160. rc = _cmThWaitForState(t,waitId);
  161. if( rc != kOkThRC )
  162. _cmThError(&t->err,rc,0,"Thread timed out waiting for '%s'.", pauseFl ? "pause" : "un-pause");
  163. return rc;
  164. }
  165. cmThStateId_t cmThreadState( cmThreadH_t h )
  166. {
  167. cmThThread_t* tp = _cmThThreadFromHandle(h);
  168. if( tp == NULL )
  169. return kNotInitThId;
  170. return tp->state;
  171. }
  172. bool cmThreadIsValid( cmThreadH_t h )
  173. { return h.h != NULL; }
  174. unsigned cmThreadPauseTimeOutMicros( cmThreadH_t h )
  175. {
  176. cmThThread_t* tp = _cmThThreadFromHandle(h);
  177. return tp->pauseMicroSecs;
  178. }
  179. void cmThreadSetPauseTimeOutMicros( cmThreadH_t h, unsigned usecs )
  180. {
  181. cmThThread_t* tp = _cmThThreadFromHandle(h);
  182. tp->pauseMicroSecs = usecs;
  183. }
  184. unsigned cmThreadWaitTimeOutMicros( cmThreadH_t h )
  185. {
  186. cmThThread_t* tp = _cmThThreadFromHandle(h);
  187. return tp->waitMicroSecs;
  188. }
  189. void cmThreadSetWaitTimeOutMicros( cmThreadH_t h, unsigned usecs )
  190. {
  191. cmThThread_t* tp = _cmThThreadFromHandle(h);
  192. tp->waitMicroSecs = usecs;
  193. }
  194. bool _cmThreadTestCb( void* p )
  195. {
  196. unsigned* ip = (unsigned*)p;
  197. ip[0]++;
  198. return true;
  199. }
  200. void cmThreadTest(cmRpt_t* rpt)
  201. {
  202. cmThreadH_t th0;
  203. unsigned val = 0;
  204. if( cmThreadCreate(&th0,_cmThreadTestCb,&val,rpt) == kOkThRC )
  205. {
  206. if( cmThreadPause(th0,0) != kOkThRC )
  207. {
  208. cmRptPrintf(rpt,"Thread start failed.\n");
  209. return;
  210. }
  211. char c = 0;
  212. cmRptPrintf(rpt,"o=print p=pause s=state q=quit\n");
  213. while( c != 'q' )
  214. {
  215. c = (char)fgetc(stdin);
  216. fflush(stdin);
  217. switch(c)
  218. {
  219. case 'o':
  220. cmRptPrintf(rpt,"val: 0x%x\n",val);
  221. break;
  222. case 's':
  223. cmRptPrintf(rpt,"state=%i\n",cmThreadState(th0));
  224. break;
  225. case 'p':
  226. {
  227. cmRC_t rc;
  228. if( cmThreadState(th0) == kPausedThId )
  229. rc = cmThreadPause(th0,kWaitThFl);
  230. else
  231. rc = cmThreadPause(th0,kPauseThFl|kWaitThFl);
  232. if( rc == kOkThRC )
  233. cmRptPrintf(rpt,"new state:%i\n", cmThreadState(th0));
  234. else
  235. cmRptPrintf(rpt,"cmThreadPause() failed.");
  236. }
  237. break;
  238. case 'q':
  239. break;
  240. //default:
  241. //cmRptPrintf(rpt,"Unknown:%c\n",c);
  242. }
  243. }
  244. if( cmThreadDestroy(&th0) != kOkThRC )
  245. cmRptPrintf(rpt,"Thread destroy failed.\n");
  246. }
  247. }
  248. //-----------------------------------------------------------------------------
  249. //-----------------------------------------------------------------------------
  250. //-----------------------------------------------------------------------------
  251. typedef struct
  252. {
  253. cmErr_t err;
  254. pthread_mutex_t mutex;
  255. pthread_cond_t cvar;
  256. } cmThreadMutex_t;
  257. cmThreadMutexH_t kThreadMutexNULL = {NULL};
  258. cmThreadMutex_t* _cmThreadMutexFromHandle( cmThreadMutexH_t h )
  259. {
  260. cmThreadMutex_t* p = (cmThreadMutex_t*)h.h;
  261. assert(p != NULL);
  262. return p;
  263. }
  264. cmThRC_t cmThreadMutexCreate( cmThreadMutexH_t* hPtr, cmRpt_t* rpt )
  265. {
  266. int sysErr;
  267. cmThreadMutex_t* p = cmMemAllocZ( cmThreadMutex_t, 1 );
  268. cmErrSetup(&p->err,rpt,"Thread Mutex");
  269. if((sysErr = pthread_mutex_init(&p->mutex,NULL)) != 0 )
  270. return _cmThError(&p->err,kCreateFailThRC,sysErr,"Thread mutex create failed.");
  271. if((sysErr = pthread_cond_init(&p->cvar,NULL)) != 0 )
  272. return _cmThError(&p->err,kCreateFailThRC,sysErr,"Thread Condition var. create failed.");
  273. hPtr->h = p;
  274. return kOkThRC;
  275. }
  276. cmThRC_t cmThreadMutexDestroy( cmThreadMutexH_t* hPtr )
  277. {
  278. int sysErr;
  279. cmThreadMutex_t* p = _cmThreadMutexFromHandle(*hPtr);
  280. if( p == NULL )
  281. return kInvalidHandleThRC;
  282. if((sysErr = pthread_cond_destroy(&p->cvar)) != 0)
  283. return _cmThError(&p->err,kDestroyFailThRC,sysErr,"Thread condition var. destroy failed.");
  284. if((sysErr = pthread_mutex_destroy(&p->mutex)) != 0)
  285. return _cmThError(&p->err,kDestroyFailThRC,sysErr,"Thread mutex destroy failed.");
  286. cmMemFree(p);
  287. hPtr->h = NULL;
  288. return kOkThRC;
  289. }
  290. cmThRC_t cmThreadMutexTryLock( cmThreadMutexH_t h, bool* lockFlPtr )
  291. {
  292. cmThreadMutex_t* p = _cmThreadMutexFromHandle(h);
  293. if( p == NULL )
  294. return kInvalidHandleThRC;
  295. int sysErr = pthread_mutex_trylock(&p->mutex);
  296. switch(sysErr)
  297. {
  298. case EBUSY:
  299. *lockFlPtr = false;
  300. break;
  301. case 0:
  302. *lockFlPtr = true;
  303. break;
  304. default:
  305. return _cmThError(&p->err,kLockFailThRC,sysErr,"Thread mutex try-lock failed.");;
  306. }
  307. return kOkThRC;
  308. }
  309. cmThRC_t cmThreadMutexLock( cmThreadMutexH_t h )
  310. {
  311. cmThreadMutex_t* p = _cmThreadMutexFromHandle(h);
  312. if( p == NULL )
  313. return kInvalidHandleThRC;
  314. int sysErr = pthread_mutex_lock(&p->mutex);
  315. if( sysErr == 0 )
  316. return kOkThRC;
  317. return _cmThError(&p->err,kLockFailThRC,sysErr,"Thread mutex lock failed.");
  318. }
  319. cmThRC_t cmThreadMutexUnlock( cmThreadMutexH_t h )
  320. {
  321. cmThreadMutex_t* p = _cmThreadMutexFromHandle(h);
  322. if( p == NULL )
  323. return kInvalidHandleThRC;
  324. int sysErr = pthread_mutex_unlock(&p->mutex);
  325. if( sysErr == 0 )
  326. return kOkThRC;
  327. return _cmThError(&p->err,kUnlockFailThRC,sysErr,"Thread mutex unlock failed.");
  328. }
  329. bool cmThreadMutexIsValid( cmThreadMutexH_t h )
  330. { return h.h != NULL; }
  331. cmThRC_t cmThreadMutexWaitOnCondVar( cmThreadMutexH_t h, bool lockFl )
  332. {
  333. cmThreadMutex_t* p = _cmThreadMutexFromHandle(h);
  334. if( p == NULL )
  335. return kInvalidHandleThRC;
  336. int sysErr;
  337. if( lockFl )
  338. if( (sysErr=pthread_mutex_lock(&p->mutex)) != 0 )
  339. _cmThError(&p->err,kLockFailThRC,sysErr,"Thread lock failed on cond. var. wait.");
  340. if((sysErr = pthread_cond_wait(&p->cvar,&p->mutex)) != 0 )
  341. _cmThError(&p->err,kCVarWaitFailThRC,sysErr,"Thread cond. var. wait failed.");
  342. return kOkThRC;
  343. }
  344. cmThRC_t cmThreadMutexSignalCondVar( cmThreadMutexH_t h )
  345. {
  346. int sysErr;
  347. cmThreadMutex_t* p = _cmThreadMutexFromHandle(h);
  348. if( p == NULL )
  349. return kInvalidHandleThRC;
  350. if((sysErr = pthread_cond_signal(&p->cvar)) != 0 )
  351. return _cmThError(&p->err,kCVarSignalFailThRC,sysErr,"Thread cond. var. signal failed.");
  352. return kOkThRC;
  353. }
  354. //-----------------------------------------------------------------------------
  355. //-----------------------------------------------------------------------------
  356. //-----------------------------------------------------------------------------
  357. cmTsQueueH_t cmTsQueueNullHandle = { NULL };
  358. enum { cmTsQueueBufCnt = 2 };
  359. typedef struct
  360. {
  361. unsigned allocCnt; // count of bytes allocated for the buffer
  362. unsigned fullCnt; // count of bytes used in the buffer
  363. char* basePtr; // base of buffer memory
  364. unsigned* msgPtr; // pointer to first msg
  365. unsigned msgCnt;
  366. } cmTsQueueBuf;
  367. typedef struct
  368. {
  369. cmThreadMutexH_t mutexH;
  370. cmTsQueueBuf bufArray[cmTsQueueBufCnt];
  371. unsigned inBufIdx;
  372. unsigned outBufIdx;
  373. char* memPtr;
  374. cmTsQueueCb_t cbFunc;
  375. void* userCbPtr;
  376. } cmTsQueue_t;
  377. cmTsQueue_t* _cmTsQueueFromHandle( cmTsQueueH_t h )
  378. {
  379. cmTsQueue_t* p = h.h;
  380. assert(p != NULL);
  381. return p;
  382. }
  383. cmThRC_t _cmTsQueueDestroy( cmTsQueue_t* p )
  384. {
  385. cmThRC_t rc;
  386. if( p == NULL )
  387. return kInvalidHandleThRC;
  388. if( p->mutexH.h != NULL )
  389. if((rc = cmThreadMutexDestroy(&p->mutexH)) != kOkThRC )
  390. return rc;
  391. if( p->memPtr != NULL )
  392. cmMemPtrFree(&p->memPtr);
  393. cmMemPtrFree(&p);
  394. return kOkThRC;
  395. }
  396. cmThRC_t cmTsQueueCreate( cmTsQueueH_t* hPtr, unsigned bufByteCnt, cmTsQueueCb_t cbFunc, void* userCbPtr, cmRpt_t* rpt )
  397. {
  398. cmTsQueue_t* p = cmMemAllocZ( cmTsQueue_t, 1 );
  399. unsigned i;
  400. if( cmThreadMutexCreate(&p->mutexH,rpt) != kOkThRC )
  401. goto errLabel;
  402. p->memPtr = cmMemAllocZ( char, bufByteCnt*cmTsQueueBufCnt );
  403. p->outBufIdx = 0;
  404. p->inBufIdx = 1;
  405. p->cbFunc = cbFunc;
  406. p->userCbPtr = userCbPtr;
  407. for(i=0; i<cmTsQueueBufCnt; ++i)
  408. {
  409. p->bufArray[i].allocCnt = bufByteCnt;
  410. p->bufArray[i].fullCnt = 0;
  411. p->bufArray[i].basePtr = p->memPtr + (i*bufByteCnt);
  412. p->bufArray[i].msgPtr = NULL;
  413. p->bufArray[i].msgCnt = 0;
  414. }
  415. hPtr->h = p;
  416. return kOkThRC;
  417. errLabel:
  418. _cmTsQueueDestroy(p);
  419. return kCreateFailThRC;
  420. }
  421. cmThRC_t cmTsQueueDestroy( cmTsQueueH_t* hPtr )
  422. {
  423. cmThRC_t rc = kOkThRC;
  424. if( (hPtr != NULL) && cmTsQueueIsValid(*hPtr))
  425. if((rc = _cmTsQueueDestroy(_cmTsQueueFromHandle(*hPtr))) == kOkThRC )
  426. hPtr->h = NULL;
  427. return rc;
  428. }
  429. cmThRC_t cmTsQueueSetCallback( cmTsQueueH_t h, cmTsQueueCb_t cbFunc, void* cbArg )
  430. {
  431. cmTsQueue_t* p = _cmTsQueueFromHandle(h);
  432. p->cbFunc = cbFunc;
  433. p->userCbPtr = cbArg;
  434. return kOkThRC;
  435. }
  436. unsigned cmTsQueueAllocByteCount( cmTsQueueH_t h )
  437. {
  438. cmTsQueue_t* p = _cmTsQueueFromHandle(h);
  439. unsigned n = 0;
  440. if( cmThreadMutexLock(p->mutexH) == kOkThRC )
  441. {
  442. n = p->bufArray[ p->inBufIdx ].allocCnt;
  443. cmThreadMutexUnlock(p->mutexH);
  444. }
  445. return n;
  446. }
  447. unsigned cmTsQueueAvailByteCount( cmTsQueueH_t h )
  448. {
  449. cmTsQueue_t* p = _cmTsQueueFromHandle(h);
  450. unsigned n = 0;
  451. if(cmThreadMutexLock(p->mutexH) == kOkThRC )
  452. {
  453. n = p->bufArray[ p->inBufIdx ].allocCnt - p->bufArray[ p->inBufIdx].fullCnt;
  454. cmThreadMutexUnlock(p->mutexH);
  455. }
  456. return n;
  457. }
  458. cmThRC_t _cmTsQueueEnqueueMsg( cmTsQueueH_t h, const void* msgPtrArray[], unsigned msgByteCntArray[], unsigned arrayCnt )
  459. {
  460. cmThRC_t rc;
  461. cmTsQueue_t* p = _cmTsQueueFromHandle(h);
  462. if( p == NULL )
  463. return kInvalidHandleThRC;
  464. // lock the mutex
  465. if((rc = cmThreadMutexLock(p->mutexH)) == kOkThRC )
  466. {
  467. cmTsQueueBuf* b = p->bufArray + p->inBufIdx; // ptr to buf recd
  468. const char* ep = b->basePtr + b->allocCnt; // end of buf data space
  469. unsigned *mp = (unsigned*)(b->basePtr + b->fullCnt); // ptr to size of new msg space
  470. char* dp = (char*)(mp+1); // ptr to data area of new msg space
  471. unsigned ttlByteCnt = 0; // track size of msg data
  472. unsigned i = 0;
  473. // get the total size of the msg
  474. for(i=0; i<arrayCnt; ++i)
  475. ttlByteCnt += msgByteCntArray[i];
  476. // if the msg is too big for the queue buf
  477. if( dp + ttlByteCnt > ep )
  478. rc = kBufFullThRC;
  479. else
  480. {
  481. // for each segment of the incoming msg
  482. for(i=0; i<arrayCnt; ++i)
  483. {
  484. // get the size of the segment
  485. unsigned n = msgByteCntArray[i];
  486. // copy in the segment
  487. memcpy(dp,msgPtrArray[i],n);
  488. dp += n; //
  489. }
  490. assert(dp <= ep );
  491. // write the size ofthe msg into the buffer
  492. *mp = ttlByteCnt;
  493. // update the pointer to the first msg
  494. if( b->msgPtr == NULL )
  495. b->msgPtr = mp;
  496. // track the count of msgs in this buffer
  497. ++b->msgCnt;
  498. // update fullCnt last since dequeue uses fullCnt to
  499. // notice that a msg may be waiting
  500. b->fullCnt += sizeof(unsigned) + ttlByteCnt;
  501. }
  502. cmThreadMutexUnlock(p->mutexH);
  503. }
  504. return rc;
  505. }
  506. cmThRC_t cmTsQueueEnqueueSegMsg( cmTsQueueH_t h, const void* msgPtrArray[], unsigned msgByteCntArray[], unsigned arrayCnt )
  507. { return _cmTsQueueEnqueueMsg(h,msgPtrArray,msgByteCntArray,arrayCnt); }
  508. cmThRC_t cmTsQueueEnqueueMsg( cmTsQueueH_t h, const void* dataPtr, unsigned byteCnt )
  509. {
  510. const void* msgPtrArray[] = { dataPtr };
  511. unsigned msgByteCntArray[] = { byteCnt };
  512. return _cmTsQueueEnqueueMsg(h,msgPtrArray,msgByteCntArray,1);
  513. }
  514. cmThRC_t cmTsQueueEnqueueIdMsg( cmTsQueueH_t h, unsigned id, const void* dataPtr, unsigned byteCnt )
  515. {
  516. const void* msgPtrArray[] = { &id, dataPtr };
  517. unsigned msgByteCntArray[] = { sizeof(id), byteCnt };
  518. return _cmTsQueueEnqueueMsg(h,msgPtrArray,msgByteCntArray,2);
  519. }
  520. cmThRC_t _cmTsQueueDequeueMsg( cmTsQueue_t* p, void* retBuf, unsigned refBufByteCnt )
  521. {
  522. cmTsQueueBuf* b = p->bufArray + p->outBufIdx;
  523. // if the output buffer is empty - there is nothing to do
  524. if( b->fullCnt == 0 )
  525. return kBufEmptyThRC;
  526. assert( b->msgPtr != NULL );
  527. // get the output msg size and data
  528. unsigned msgByteCnt = *b->msgPtr;
  529. char* msgDataPtr = (char*)(b->msgPtr + 1);
  530. // transmit the msg via a callback
  531. if( retBuf == NULL && p->cbFunc != NULL )
  532. p->cbFunc(p->userCbPtr,msgByteCnt,msgDataPtr);
  533. else
  534. {
  535. // retBuf may be NULL if the func is being used by cmTsQueueDequeueByteCount()
  536. if( retBuf == NULL || msgByteCnt > refBufByteCnt )
  537. return kBufTooSmallThRC;
  538. // copy the msg to a buffer
  539. if( retBuf != NULL )
  540. memcpy(retBuf,msgDataPtr,msgByteCnt);
  541. }
  542. // update the buffer
  543. b->fullCnt -= sizeof(unsigned) + msgByteCnt;
  544. b->msgPtr = (unsigned*)(msgDataPtr + msgByteCnt);
  545. --(b->msgCnt);
  546. if( b->fullCnt == 0 )
  547. {
  548. assert(b->msgCnt == 0);
  549. b->msgPtr = NULL;
  550. }
  551. return kOkThRC;
  552. }
  553. cmThRC_t cmTsQueueDequeueMsg( cmTsQueueH_t h, void* retBuf, unsigned refBufByteCnt )
  554. {
  555. cmThRC_t rc;
  556. cmTsQueue_t* p = _cmTsQueueFromHandle(h);
  557. if( p == NULL )
  558. return kInvalidHandleThRC;
  559. // dequeue the next msg from the current output buffer
  560. if((rc =_cmTsQueueDequeueMsg( p, retBuf, refBufByteCnt )) != kBufEmptyThRC )
  561. return rc;
  562. // the current output buffer was empty
  563. cmTsQueueBuf* b = p->bufArray + p->inBufIdx;
  564. // if the input buffer has msg's ...
  565. if( b->fullCnt > 0 )
  566. {
  567. bool lockFl = false;
  568. // ...attempt to lock the mutex ...
  569. if( (cmThreadMutexTryLock(p->mutexH,&lockFl) == kOkThRC) && lockFl )
  570. {
  571. // ... swap the input and the output buffers ...
  572. unsigned tmp = p->inBufIdx;
  573. p->inBufIdx = p->outBufIdx;
  574. p->outBufIdx = tmp;
  575. // .. unlock the mutex
  576. cmThreadMutexUnlock(p->mutexH);
  577. // ... and dequeue the first msg from the new output buffer
  578. rc = _cmTsQueueDequeueMsg( p, retBuf, refBufByteCnt );
  579. }
  580. }
  581. return rc;
  582. }
  583. bool cmTsQueueMsgWaiting( cmTsQueueH_t h )
  584. {
  585. cmTsQueue_t* p = _cmTsQueueFromHandle(h);
  586. if( p == NULL )
  587. return false;
  588. if( p->bufArray[p->outBufIdx].fullCnt )
  589. return true;
  590. return p->bufArray[p->inBufIdx].fullCnt > 0;
  591. }
  592. unsigned cmTsQueueDequeueMsgByteCount( cmTsQueueH_t h )
  593. {
  594. cmTsQueue_t* p = _cmTsQueueFromHandle(h);
  595. if( p == NULL )
  596. return 0;
  597. // if output msgs are available then the msgPtr points to the size of the msg
  598. if( p->bufArray[p->outBufIdx].fullCnt )
  599. return *(p->bufArray[p->outBufIdx].msgPtr);
  600. // no msgs are waiting in the output buffer
  601. // force the buffers to swap - returns kBufEmptyThRC if there are
  602. // still no msgs waiting after the swap (the input buf was also empty)
  603. if( cmTsQueueDequeueMsg(h,NULL,0) == kBufTooSmallThRC )
  604. {
  605. // the buffers swapped so there must be msg waiting
  606. assert( p->bufArray[p->outBufIdx].fullCnt );
  607. return *(p->bufArray[p->outBufIdx].msgPtr);
  608. }
  609. return 0;
  610. }
  611. bool cmTsQueueIsValid( cmTsQueueH_t h )
  612. { return h.h != NULL; }
  613. //--------------------------------------------------------------------------------------------------
  614. //--------------------------------------------------------------------------------------------------
  615. //--------------------------------------------------------------------------------------------------
  616. //--------------------------------------------------------------------------------------------------
  617. //--------------------------------------------------------------------------------------------------
  618. //--------------------------------------------------------------------------------------------------
  619. typedef struct
  620. {
  621. volatile unsigned ii;
  622. cmErr_t err;
  623. char* buf;
  624. unsigned bn;
  625. cmTsQueueCb_t cbFunc;
  626. void* cbArg;
  627. volatile unsigned oi;
  628. } cmTs1p1c_t;
  629. cmTs1p1c_t* _cmTs1p1cHandleToPtr( cmTs1p1cH_t h )
  630. {
  631. cmTs1p1c_t* p = (cmTs1p1c_t*)h.h;
  632. assert( p != NULL );
  633. return p;
  634. }
  635. cmThRC_t cmTs1p1cCreate( cmTs1p1cH_t* hPtr, unsigned bufByteCnt, cmTsQueueCb_t cbFunc, void* cbArg, cmRpt_t* rpt )
  636. {
  637. cmThRC_t rc;
  638. if((rc = cmTs1p1cDestroy(hPtr)) != kOkThRC )
  639. return rc;
  640. cmTs1p1c_t* p = cmMemAllocZ(cmTs1p1c_t,1);
  641. cmErrSetup(&p->err,rpt,"1p1c Queue");
  642. p->buf = cmMemAllocZ(char,bufByteCnt+sizeof(unsigned));
  643. p->ii = 0;
  644. p->oi = 0;
  645. p->bn = bufByteCnt;
  646. p->cbFunc = cbFunc;
  647. p->cbArg = cbArg;
  648. hPtr->h = p;
  649. return rc;
  650. }
  651. cmThRC_t cmTs1p1cDestroy( cmTs1p1cH_t* hp )
  652. {
  653. cmThRC_t rc = kOkThRC;
  654. if( hp == NULL || cmTs1p1cIsValid(*hp)==false )
  655. return kOkThRC;
  656. cmTs1p1c_t* p = _cmTs1p1cHandleToPtr(*hp);
  657. cmMemFree(p->buf);
  658. cmMemFree(p);
  659. hp->h = NULL;
  660. return rc;
  661. }
  662. cmThRC_t cmTs1p1cSetCallback( cmTs1p1cH_t h, cmTsQueueCb_t cbFunc, void* cbArg )
  663. {
  664. cmTs1p1c_t* p = _cmTs1p1cHandleToPtr(h);
  665. p->cbFunc = cbFunc;
  666. p->cbArg = cbArg;
  667. return kOkThRC;
  668. }
  669. cmThRC_t cmTs1p1cEnqueueSegMsg( cmTs1p1cH_t h, const void* msgPtrArray[], unsigned msgByteCntArray[], unsigned arrayCnt )
  670. {
  671. cmThRC_t rc = kOkThRC;
  672. unsigned mn = 0;
  673. unsigned i;
  674. cmTs1p1c_t* p = _cmTs1p1cHandleToPtr(h);
  675. // get the total count of bytes for this msg
  676. for(i=0; i<arrayCnt; ++i)
  677. mn += msgByteCntArray[i];
  678. int dn = mn + sizeof(unsigned);
  679. int oi = p->oi;
  680. int bi = p->ii; // 'bi' is the idx of the leftmost cell which can be written
  681. int en = p->bn; // 'en' is the idx of the cell just to the right of the rightmost cell that can be written
  682. // note: If 'oi' marks the rightmost location then 'en' must be set
  683. // one cell to the left of 'oi', because 'ii' can never be allowed to
  684. // advance onto 'oi' - because 'oi'=='ii' marks an empty (NOT a full)
  685. // queue.
  686. //
  687. // If 'bn' marks the rightmost location then 'ii' can advance onto 'bn'
  688. // beause the true queue length is bn+1.
  689. // if we need to wrap
  690. if( en-bi < dn && oi<=bi )
  691. {
  692. bi = 0;
  693. en = oi - 1; // note if oi==0 then en is negative - see note above re: oi==ii
  694. assert( p->ii>=0 && p->ii <= p->bn );
  695. *(unsigned*)(p->buf + p->ii) = cmInvalidIdx; // mark the wrap location
  696. }
  697. // if oi is between ii and bn
  698. if( oi > bi )
  699. en = oi - 1; // never allow ii to advance onto oi - see note above
  700. // if the msg won't fit
  701. if( en - bi < dn )
  702. return cmErrMsg(&p->err,kBufFullThRC,"%i consecutive bytes is not available in the queue.",dn);
  703. // set the msg byte count - the msg byte cnt precedes the msg body
  704. char* dp = p->buf + bi;
  705. *(unsigned*)dp = dn - sizeof(unsigned);
  706. dp += sizeof(unsigned);
  707. // copy the msg into the buffer
  708. for(i=0,dn=0; i<arrayCnt; ++i)
  709. {
  710. memcpy(dp,msgPtrArray[i],msgByteCntArray[i]);
  711. dp += msgByteCntArray[i];
  712. dn += msgByteCntArray[i];
  713. }
  714. // incrementing p->ii must occur last - the unnecessary accumulation
  715. // of dn in the above loop is intended to prevent this line from
  716. // begin moved before the copy loop.
  717. p->ii = bi + dn + sizeof(unsigned);
  718. assert( p->ii >= 0 && p->ii <= p->bn);
  719. return rc;
  720. }
  721. cmThRC_t cmTs1p1cEnqueueMsg( cmTs1p1cH_t h, const void* dataPtr, unsigned byteCnt )
  722. { return cmTs1p1cEnqueueSegMsg(h,&dataPtr,&byteCnt,1); }
  723. unsigned cmTs1p1cAllocByteCount( cmTs1p1cH_t h )
  724. {
  725. cmTs1p1c_t* p = _cmTs1p1cHandleToPtr(h);
  726. return p->bn;
  727. }
  728. unsigned cmTs1p1cAvailByteCount( cmTs1p1cH_t h )
  729. {
  730. cmTs1p1c_t* p = _cmTs1p1cHandleToPtr(h);
  731. unsigned oi = p->oi;
  732. unsigned ii = p->ii;
  733. return oi < ii ? p->bn - ii + oi : oi - ii;
  734. }
  735. unsigned _cmTs1p1cDequeueMsgByteCount( cmTs1p1c_t* p )
  736. {
  737. // if the buffer is empty
  738. if( p->ii == p->oi )
  739. return 0;
  740. // get the length of the next msg
  741. unsigned mn = *(unsigned*)(p->buf + p->oi);
  742. // if the msg length is cmInvalidIdx ...
  743. if( mn == cmInvalidIdx )
  744. {
  745. p->oi = 0; // ... wrap to buf begin and try again
  746. return _cmTs1p1cDequeueMsgByteCount(p);
  747. }
  748. return mn;
  749. }
  750. cmThRC_t cmTs1p1cDequeueMsg( cmTs1p1cH_t h, void* dataPtr, unsigned byteCnt )
  751. {
  752. cmThRC_t rc = kOkThRC;
  753. cmTs1p1c_t* p = _cmTs1p1cHandleToPtr(h);
  754. unsigned mn;
  755. if((mn = _cmTs1p1cDequeueMsgByteCount(p)) == 0 )
  756. return kBufEmptyThRC;
  757. void* mp = p->buf + p->oi + sizeof(unsigned);
  758. if( dataPtr != NULL )
  759. {
  760. if( byteCnt < mn )
  761. return cmErrMsg(&p->err,kBufTooSmallThRC,"The return buffer constains too few bytes (%i) to contain %i bytes.",byteCnt,mn);
  762. memcpy(dataPtr,mp,mn);
  763. }
  764. else
  765. {
  766. p->cbFunc(p->cbArg,mn,mp);
  767. }
  768. p->oi += mn + sizeof(unsigned);
  769. return rc;
  770. }
  771. unsigned cmTs1p1cDequeueMsgByteCount( cmTs1p1cH_t h )
  772. {
  773. cmTs1p1c_t* p = _cmTs1p1cHandleToPtr(h);
  774. return _cmTs1p1cDequeueMsgByteCount(p);
  775. }
  776. bool cmTs1p1cMsgWaiting( cmTs1p1cH_t h )
  777. { return cmTs1p1cDequeueMsgByteCount(h) > 0; }
  778. bool cmTs1p1cIsValid( cmTs1p1cH_t h )
  779. { return h.h != NULL; }
  780. //============================================================================================================================
  781. bool cmThIntCAS( int* addr, int old, int new )
  782. {
  783. #ifdef OS_OSX
  784. int rv = OSAtomicCompareAndSwap32Barrier(old,new,addr);
  785. return rv;
  786. #endif
  787. #ifdef OS_LINUX
  788. return __sync_bool_compare_and_swap(addr,old,new);
  789. #endif
  790. }
  791. bool cmThUIntCAS( unsigned* addr, unsigned old, unsigned new )
  792. {
  793. #ifdef OS_OSX
  794. return OSAtomicCompareAndSwap32Barrier((int)old,(int)new,(int*)addr);
  795. #endif
  796. #ifdef OS_LINUX
  797. return __sync_bool_compare_and_swap(addr,old,new);
  798. #endif
  799. }
  800. bool cmThFloatCAS( float* addr, float old, float new )
  801. {
  802. #ifdef OS_OSX
  803. return OSAtomicCompareAndSwap32Barrier(*(int*)(&old),*(int*)(&new),(int*)addr );
  804. #endif
  805. #ifdef OS_LINUX
  806. // If we use pointer aliasing to pun the pointer types then it will violate the
  807. // strict pointer aliasing rules used by -O2. Instead we use this union
  808. // punning scheme which in theory should always work in C99 (although no C++).
  809. typedef union
  810. {
  811. unsigned* up;
  812. float* fp;
  813. } u;
  814. u u0,u1;
  815. u0.fp = &old;
  816. u1.fp = &new;
  817. return __sync_bool_compare_and_swap((unsigned*)addr,*u0.up,*u1.up);
  818. #endif
  819. }
  820. bool cmThPtrCAS( void* addr, void* old, void* neww )
  821. {
  822. #ifdef OS_OSX
  823. // REMOVE THIS HACK AND USE OSAtomicCompareAndSwapPtrBarrier() WHEN
  824. // A 64 BIT BUILD IS POSSIBLE ON OS-X.
  825. typedef struct
  826. {
  827. union
  828. {
  829. void* addr;
  830. #ifdef OSX_VER_10_5
  831. int val;
  832. #else
  833. int64_t val;
  834. #endif
  835. } u;
  836. } s_t;
  837. s_t ov,nv;
  838. ov.u.addr = old;
  839. nv.u.addr = neww;
  840. #ifdef OSX_VER_10_5
  841. int rv = OSAtomicCompareAndSwap32Barrier(ov.u.val,nv.u.val,(int*)addr);
  842. #else
  843. int rv = OSAtomicCompareAndSwap64Barrier(ov.u.val,nv.u.val,(int64_t*)addr);
  844. #endif
  845. return rv;
  846. #endif
  847. #ifdef OS_LINUX
  848. #ifdef OS_64
  849. return __sync_bool_compare_and_swap((long long*)addr, (long long)old, (long long)neww);
  850. #else
  851. return __sync_bool_compare_and_swap((int*)addr,(int)old,(int)neww);
  852. #endif
  853. #endif
  854. }
  855. void cmThIntIncr( int* addr, int incr )
  856. {
  857. #ifdef OS_OSX
  858. OSAtomicAdd32Barrier(incr,addr);
  859. #endif
  860. #ifdef OS_LINUX
  861. // ... could also use __sync_add_and_fetch() ...
  862. __sync_fetch_and_add(addr,incr);
  863. #endif
  864. }
  865. void cmThUIntIncr( unsigned* addr, unsigned incr )
  866. {
  867. #ifdef OS_OSX
  868. OSAtomicAdd32Barrier((int)incr,(int*)addr);
  869. #endif
  870. #ifdef OS_LINUX
  871. __sync_fetch_and_add(addr,incr);
  872. #endif
  873. }
  874. void cmThFloatIncr(float* addr, float incr )
  875. {
  876. float old,new;
  877. do
  878. {
  879. old = *addr;
  880. new = old + incr;
  881. }while( cmThFloatCAS(addr,old,new)==0 );
  882. }
  883. void cmThIntDecr( int* addr, int decr )
  884. {
  885. #ifdef OS_OSX
  886. OSAtomicAdd32Barrier(-decr,addr);
  887. #endif
  888. #ifdef OS_LINUX
  889. __sync_fetch_and_sub(addr,decr);
  890. #endif
  891. }
  892. void cmThUIntDecr( unsigned* addr, unsigned decr )
  893. {
  894. #ifdef OS_OSX
  895. OSAtomicAdd32Barrier(-((int)decr),(int*)addr);
  896. #endif
  897. #ifdef OS_LINUX
  898. __sync_fetch_and_sub(addr,decr);
  899. #endif
  900. }
  901. void cmThFloatDecr(float* addr, float decr )
  902. {
  903. float old,new;
  904. do
  905. {
  906. old = *addr;
  907. new = old - decr;
  908. }while( cmThFloatCAS(addr,old,new)==0 );
  909. }
  910. //============================================================================================================================
  911. //
  912. //
  913. typedef pthread_t cmThreadId_t;
  914. typedef struct
  915. {
  916. cmThreadId_t id; // id of this thread as returned by pthread_self()
  917. char* buf; // buf[bn]
  918. int ii; // input index
  919. int oi; // output index (oi==ii == empty buffer)
  920. } cmTsBuf_t;
  921. // msg header - which is actually written AFTER the msg it is associated with
  922. typedef struct cmTsHdr_str
  923. {
  924. int mn; // length of the msg
  925. int ai; // buffer index
  926. struct cmTsHdr_str* link; // pointer to next msg
  927. } cmTsHdr_t;
  928. typedef struct
  929. {
  930. cmErr_t err;
  931. int bn; // bytes per thread buffer
  932. cmTsBuf_t* a; // a[an] buffer array
  933. unsigned an; // length of a[] - one buffer per thread
  934. cmTsQueueCb_t cbFunc;
  935. void* cbArg;
  936. cmTsHdr_t* ilp; // prev msg hdr record
  937. cmTsHdr_t* olp; // prev msg hdr record (wait for olp->link to be set to go to next record)
  938. } cmTsMp1c_t;
  939. cmTsMp1cH_t cmTsMp1cNullHandle = cmSTATIC_NULL_HANDLE;
  940. void _cmTsMp1cPrint( cmTsMp1c_t* p )
  941. {
  942. unsigned i;
  943. for(i=0; i<p->an; ++i)
  944. printf("%2i ii:%3i oi:%3i\n",i,p->a[i].ii,p->a[i].oi);
  945. }
  946. cmTsMp1c_t* _cmTsMp1cHandleToPtr( cmTsMp1cH_t h )
  947. {
  948. cmTsMp1c_t* p = (cmTsMp1c_t*)h.h;
  949. assert(p != NULL);
  950. return p;
  951. }
  952. unsigned _cmTsMp1cBufIndex( cmTsMp1c_t* p, cmThreadId_t id )
  953. {
  954. unsigned i;
  955. for(i=0; i<p->an; ++i)
  956. if( p->a[i].id == id )
  957. return i;
  958. p->an = i+1;
  959. p->a = cmMemResizePZ(cmTsBuf_t,p->a,p->an);
  960. p->a[i].buf = cmMemAllocZ(char,p->bn);
  961. p->a[i].id = id;
  962. return i;
  963. }
  964. cmThRC_t cmTsMp1cDestroy( cmTsMp1cH_t* hp )
  965. {
  966. if( hp == NULL || cmTsMp1cIsValid(*hp) == false )
  967. return kOkThRC;
  968. cmTsMp1c_t* p = _cmTsMp1cHandleToPtr(*hp);
  969. unsigned i;
  970. for(i=0; i<p->an; ++i)
  971. cmMemFree(p->a[i].buf);
  972. cmMemPtrFree(&p->a);
  973. cmMemFree(p);
  974. hp->h = NULL;
  975. return kOkThRC;
  976. }
  977. cmThRC_t cmTsMp1cCreate( cmTsMp1cH_t* hp, unsigned bufByteCnt, cmTsQueueCb_t cbFunc, void* cbArg, cmRpt_t* rpt )
  978. {
  979. cmThRC_t rc;
  980. if((rc = cmTsMp1cDestroy(hp)) != kOkThRC )
  981. return rc;
  982. cmTsMp1c_t* p = cmMemAllocZ(cmTsMp1c_t,1);
  983. cmErrSetup(&p->err,rpt,"TsMp1c Queue");
  984. p->a = NULL;
  985. p->an = 0;
  986. p->bn = bufByteCnt;
  987. p->cbFunc = cbFunc;
  988. p->cbArg = cbArg;
  989. p->ilp = NULL;
  990. p->olp = NULL;
  991. hp->h = p;
  992. return rc;
  993. }
  994. void cmTsMp1cSetCbFunc( cmTsMp1cH_t h, cmTsQueueCb_t cbFunc, void* cbArg )
  995. {
  996. cmTsMp1c_t* p = _cmTsMp1cHandleToPtr(h);
  997. p->cbFunc = cbFunc;
  998. p->cbArg = cbArg;
  999. }
  1000. cmTsQueueCb_t cmTsMp1cCbFunc( cmTsMp1cH_t h )
  1001. {
  1002. cmTsMp1c_t* p = _cmTsMp1cHandleToPtr(h);
  1003. return p->cbFunc;
  1004. }
  1005. void* cmTsMp1cCbArg( cmTsMp1cH_t h )
  1006. {
  1007. cmTsMp1c_t* p = _cmTsMp1cHandleToPtr(h);
  1008. return p->cbArg;
  1009. }
  1010. //#define CAS(addr,old,new) __sync_bool_compare_and_swap(addr,old,new)
  1011. //#define CAS(addr,old,neww) cmThPtrCAS(addr,old,neww)
  1012. cmThRC_t cmTsMp1cEnqueueSegMsg( cmTsMp1cH_t h, const void* msgPtrArray[], unsigned msgByteCntArray[], unsigned arrayCnt )
  1013. {
  1014. cmThRC_t rc = kOkThRC;
  1015. unsigned mn = 0;
  1016. cmTsMp1c_t* p = _cmTsMp1cHandleToPtr(h);
  1017. unsigned ai = _cmTsMp1cBufIndex( p, pthread_self() );
  1018. cmTsBuf_t* b = p->a + ai;
  1019. int i,bi,ei;
  1020. cmTsHdr_t hdr;
  1021. // Use a stored oi for the duration of this function.
  1022. // b->oi may be changed by the dequeue thread but storing it here
  1023. // at least prevents it from changing during the course of the this function.
  1024. // Note: b->oi is only used to check for buffer full. Even if it changes
  1025. // it would only mean that more bytes were available than calculated based
  1026. // on the stored value. A low estimate of the actual bytes available is
  1027. // never unsafe.
  1028. volatile int oi = b->oi;
  1029. // get the total count of bytes for this msg
  1030. for(i=0; i<arrayCnt; ++i)
  1031. mn += msgByteCntArray[i];
  1032. // dn = count of msg bytes + count of header bytes
  1033. int dn = mn + sizeof(hdr);
  1034. // if oi is ahead of ii in the queue then we must write
  1035. // in the area between ii and oi
  1036. if( oi > b->ii )
  1037. {
  1038. ei = oi-1; // (never allow ii to equal oi (that's the empty condition))
  1039. bi = b->ii;
  1040. }
  1041. else // otherwise oi is same or before ii in the queue and we have the option to wrap
  1042. {
  1043. // if the new msg will not fit at the end of the queue ....
  1044. if( b->ii + dn > p->bn )
  1045. {
  1046. bi = 0; // ... then wrap to the beginning
  1047. ei = oi-1; // (never allow ii to equal oi (that's the empty condition))
  1048. }
  1049. else
  1050. {
  1051. ei = p->bn; // otherwise write at the current location
  1052. bi = b->ii;
  1053. }
  1054. }
  1055. if( bi + dn > ei )
  1056. return cmErrMsg(&p->err,kBufFullThRC,"%i consecutive bytes is not available in the queue.",dn);
  1057. char* dp = b->buf + bi;
  1058. // write the msg
  1059. for(i=0; i<arrayCnt; ++i)
  1060. {
  1061. memcpy(dp,msgPtrArray[i],msgByteCntArray[i]);
  1062. dp += msgByteCntArray[i];
  1063. }
  1064. // setup the msg header
  1065. hdr.ai = ai;
  1066. hdr.mn = mn;
  1067. hdr.link = NULL;
  1068. // write the msg header (following the msg body in memory)
  1069. cmTsHdr_t* hp = (cmTsHdr_t*)dp;
  1070. memcpy(hp,&hdr,sizeof(hdr));
  1071. // increment the buffers input index
  1072. b->ii = bi + dn;
  1073. // update the link list head to point to this msg hdr
  1074. cmTsHdr_t* old_hp, *new_hp;
  1075. do
  1076. {
  1077. old_hp = p->ilp;
  1078. new_hp = hp;
  1079. }while(!cmThPtrCAS(&p->ilp,old_hp,new_hp));
  1080. // link the prev recd to this recd
  1081. if( old_hp != NULL )
  1082. old_hp->link = hp;
  1083. // if this is the first record written by this queue then prime the output list
  1084. do
  1085. {
  1086. old_hp = p->olp;
  1087. new_hp = hp;
  1088. if( old_hp != NULL )
  1089. break;
  1090. }while(!cmThPtrCAS(&p->olp,old_hp,new_hp));
  1091. //printf("%p %p %i\n",p->ilp,p->olp,p->olp->mn);
  1092. return rc;
  1093. }
  1094. cmThRC_t cmTsMp1cEnqueueMsg( cmTsMp1cH_t h, const void* dataPtr, unsigned byteCnt )
  1095. { return cmTsMp1cEnqueueSegMsg(h,&dataPtr,&byteCnt,1); }
  1096. unsigned cmTsMp1cAllocByteCount( cmTsMp1cH_t h )
  1097. {
  1098. cmTsMp1c_t* p = _cmTsMp1cHandleToPtr(h);
  1099. return p->bn;
  1100. }
  1101. unsigned cmTsMp1cAvailByteCount( cmTsMp1cH_t h )
  1102. {
  1103. cmTsMp1c_t* p = _cmTsMp1cHandleToPtr(h);
  1104. unsigned ai = _cmTsMp1cBufIndex(p,pthread_self());
  1105. const cmTsBuf_t* b = p->a + ai;
  1106. if( b->oi > b->ii )
  1107. return b->oi - b->ii - 1;
  1108. return (p->bn - b->ii) + b->oi - 1;
  1109. }
  1110. unsigned _cmTsMp1cNextMsgByteCnt( cmTsMp1c_t* p )
  1111. {
  1112. if( p->olp == NULL )
  1113. return 0;
  1114. // if the current msg has not yet been read
  1115. if( p->olp->mn != 0 )
  1116. return p->olp->mn;
  1117. // if the current msg has been read but a new next msg has been linked
  1118. if( p->olp->mn == 0 && p->olp->link != NULL )
  1119. {
  1120. // advance the buffer output msg past the prev msg header
  1121. char* hp = (char*)(p->olp + 1);
  1122. p->a[p->olp->ai].oi = hp - p->a[p->olp->ai].buf;
  1123. // advance msg pointer to point to the new msg header
  1124. p->olp = p->olp->link;
  1125. // return the size of the new msg
  1126. return p->olp->mn;
  1127. }
  1128. return 0;
  1129. }
  1130. cmThRC_t cmTsMp1cDequeueMsg( cmTsMp1cH_t h, void* dataPtr, unsigned byteCnt )
  1131. {
  1132. cmTsMp1c_t* p = _cmTsMp1cHandleToPtr(h);
  1133. // if there are no messages waiting
  1134. if( _cmTsMp1cNextMsgByteCnt(p) == 0 )
  1135. return kBufEmptyThRC;
  1136. char* hp = (char*)p->olp;
  1137. char* dp = hp - p->olp->mn; // the msg body is before the msg hdr
  1138. if( dataPtr == NULL )
  1139. {
  1140. p->cbFunc(p->cbArg,p->olp->mn,dp);
  1141. }
  1142. else
  1143. {
  1144. if( p->olp->mn > byteCnt )
  1145. return cmErrMsg(&p->err,kBufTooSmallThRC,"The return buffer constains too few bytes (%i) to contain %i bytes.",byteCnt,p->olp->mn);
  1146. memcpy(dataPtr,dp,p->olp->mn);
  1147. }
  1148. // advance the buffers output index past the msg body
  1149. p->a[p->olp->ai].oi = hp - p->a[p->olp->ai].buf;
  1150. // mark the msg as read
  1151. p->olp->mn = 0;
  1152. return kOkThRC;
  1153. }
  1154. bool cmTsMp1cMsgWaiting( cmTsMp1cH_t h )
  1155. {
  1156. cmTsMp1c_t* p = _cmTsMp1cHandleToPtr(h);
  1157. return _cmTsMp1cNextMsgByteCnt(p) != 0;
  1158. }
  1159. unsigned cmTsMp1cDequeueMsgByteCount( cmTsMp1cH_t h )
  1160. {
  1161. cmTsMp1c_t* p = _cmTsMp1cHandleToPtr(h);
  1162. return _cmTsMp1cNextMsgByteCnt(p);
  1163. }
  1164. bool cmTsMp1cIsValid( cmTsMp1cH_t h )
  1165. { return h.h != NULL; }
  1166. //============================================================================================================================/
  1167. //
  1168. // cmTsQueueTest()
  1169. //
  1170. // param recd for use by _cmTsQueueCb0() and
  1171. // the msg record passed between the sender
  1172. // threads and the receiver thread
  1173. typedef struct
  1174. {
  1175. unsigned id;
  1176. cmTsQueueH_t qH;
  1177. int val;
  1178. } _cmTsQCbParam_t;
  1179. // Generate a random number and put it in a TS queue
  1180. bool _cmTsQueueCb0(void* param)
  1181. {
  1182. _cmTsQCbParam_t* p = (_cmTsQCbParam_t*)param;
  1183. p->val = rand(); // generate a random number
  1184. // send the msg
  1185. if( cmTsQueueEnqueueMsg( p->qH, p, sizeof(_cmTsQCbParam_t)) == kOkThRC )
  1186. printf("in:%i %i\n",p->id,p->val);
  1187. else
  1188. printf("in error %i\n",p->id);
  1189. cmSleepUs(100*1000);
  1190. return true;
  1191. }
  1192. // Monitor a TS queue for incoming messages from _cmTsQueueCb1()
  1193. bool _cmTsQueueCb1(void* param)
  1194. {
  1195. // the thread param is a ptr to the TS queue to monitor.
  1196. cmTsQueueH_t* qp = (cmTsQueueH_t*)param;
  1197. cmThRC_t rc;
  1198. _cmTsQCbParam_t msg;
  1199. // dequeue any waiting messages
  1200. if((rc = cmTsQueueDequeueMsg( *qp, &msg, sizeof(msg))) == kOkThRC )
  1201. printf("out:%i %i\n",msg.id,msg.val);
  1202. else
  1203. {
  1204. if( rc != kBufEmptyThRC )
  1205. printf("out error:%i\n", rc);
  1206. }
  1207. return true;
  1208. }
  1209. // Test the TS queue by starting sender threads (threads 0 & 1)
  1210. // and a receiver thread (thread 2) and sending messages
  1211. // from the sender to the receiver.
  1212. void cmTsQueueTest( cmRpt_t* rpt )
  1213. {
  1214. cmThreadH_t th0=cmThreadNullHandle,th1=cmThreadNullHandle,th2=cmThreadNullHandle;
  1215. cmTsQueueH_t q=cmTsQueueNullHandle;
  1216. _cmTsQCbParam_t param0, param1;
  1217. // create a TS Queue
  1218. if( cmTsQueueCreate(&q,100,NULL,NULL,rpt) != kOkThRC )
  1219. goto errLabel;
  1220. // create thread 0
  1221. param0.id = 0;
  1222. param0.qH = q;
  1223. if( cmThreadCreate(&th0,_cmTsQueueCb0,&param0,rpt) != kOkThRC )
  1224. goto errLabel;
  1225. // create thread 1
  1226. param1.id = 1;
  1227. param1.qH = q;
  1228. if( cmThreadCreate(&th1,_cmTsQueueCb0,&param1,rpt) != kOkThRC )
  1229. goto errLabel;
  1230. // create thread 2
  1231. if( cmThreadCreate(&th2,_cmTsQueueCb1,&q,rpt) != kOkThRC )
  1232. goto errLabel;
  1233. // start thread 0
  1234. if( cmThreadPause(th0,0) != kOkThRC )
  1235. goto errLabel;
  1236. // start thread 1
  1237. if( cmThreadPause(th1,0) != kOkThRC )
  1238. goto errLabel;
  1239. // start thread 2
  1240. if( cmThreadPause(th2,0) != kOkThRC )
  1241. goto errLabel;
  1242. printf("any key to quit.");
  1243. getchar();
  1244. errLabel:
  1245. if( cmThreadIsValid(th0) )
  1246. if( cmThreadDestroy(&th0) != kOkThRC )
  1247. printf("Error destroying thread 0\n");
  1248. if( cmThreadIsValid(th1) )
  1249. if( cmThreadDestroy(&th1) != kOkThRC )
  1250. printf("Error destroying thread 1\n");
  1251. if( cmThreadIsValid(th2) )
  1252. if( cmThreadDestroy(&th2) != kOkThRC )
  1253. printf("Error destroying thread 1\n");
  1254. if( cmTsQueueIsValid(q) )
  1255. if( cmTsQueueDestroy(&q) != kOkThRC )
  1256. printf("Error destroying queue\n");
  1257. }
  1258. //============================================================================================================================/
  1259. //
  1260. // cmTs1p1cTest()
  1261. //
  1262. // param recd for use by _cmTsQueueCb0() and
  1263. // the msg record passed between the sender
  1264. // threads and the receiver thread
  1265. typedef struct
  1266. {
  1267. unsigned id;
  1268. cmTs1p1cH_t qH;
  1269. int val;
  1270. } _cmTs1p1cCbParam_t;
  1271. cmTs1p1cH_t cmTs1p1cNullHandle = cmSTATIC_NULL_HANDLE;
  1272. // Generate a random number and put it in a TS queue
  1273. bool _cmTs1p1cCb0(void* param)
  1274. {
  1275. _cmTs1p1cCbParam_t* p = (_cmTs1p1cCbParam_t*)param;
  1276. p->val = rand(); // generate a random number
  1277. // send the msg
  1278. if( cmTs1p1cEnqueueMsg( p->qH, p, sizeof(_cmTs1p1cCbParam_t)) == kOkThRC )
  1279. printf("in:%i %i\n",p->id,p->val);
  1280. else
  1281. printf("in error %i\n",p->id);
  1282. ++p->id;
  1283. cmSleepUs(100*1000);
  1284. return true;
  1285. }
  1286. // Monitor a TS queue for incoming messages from _cmTs1p1cCb1()
  1287. bool _cmTs1p1cCb1(void* param)
  1288. {
  1289. // the thread param is a ptr to the TS queue to monitor.
  1290. cmTs1p1cH_t* qp = (cmTs1p1cH_t*)param;
  1291. cmThRC_t rc;
  1292. _cmTs1p1cCbParam_t msg;
  1293. // dequeue any waiting messages
  1294. if((rc = cmTs1p1cDequeueMsg( *qp, &msg, sizeof(msg))) == kOkThRC )
  1295. printf("out:%i %i\n",msg.id,msg.val);
  1296. else
  1297. {
  1298. if( rc != kBufEmptyThRC )
  1299. printf("out error:%i\n", rc);
  1300. }
  1301. return true;
  1302. }
  1303. // Test the TS queue by starting sender threads (threads 0 & 1)
  1304. // and a receiver thread (thread 2) and sending messages
  1305. // from the sender to the receiver.
  1306. void cmTs1p1cTest( cmRpt_t* rpt )
  1307. {
  1308. cmThreadH_t th0=cmThreadNullHandle,th1=cmThreadNullHandle,th2=cmThreadNullHandle;
  1309. cmTs1p1cH_t q=cmTs1p1cNullHandle;
  1310. _cmTs1p1cCbParam_t param1;
  1311. // create a TS Queue
  1312. if( cmTs1p1cCreate(&q,28*2,NULL,NULL,rpt) != kOkThRC )
  1313. goto errLabel;
  1314. // create thread 1
  1315. param1.id = 0;
  1316. param1.qH = q;
  1317. if( cmThreadCreate(&th1,_cmTs1p1cCb0,&param1,rpt) != kOkThRC )
  1318. goto errLabel;
  1319. // create thread 2
  1320. if( cmThreadCreate(&th2,_cmTs1p1cCb1,&q,rpt) != kOkThRC )
  1321. goto errLabel;
  1322. // start thread 1
  1323. if( cmThreadPause(th1,0) != kOkThRC )
  1324. goto errLabel;
  1325. // start thread 2
  1326. if( cmThreadPause(th2,0) != kOkThRC )
  1327. goto errLabel;
  1328. printf("any key to quit.");
  1329. getchar();
  1330. errLabel:
  1331. if( cmThreadIsValid(th0) )
  1332. if( cmThreadDestroy(&th0) != kOkThRC )
  1333. printf("Error destroying thread 0\n");
  1334. if( cmThreadIsValid(th1) )
  1335. if( cmThreadDestroy(&th1) != kOkThRC )
  1336. printf("Error destroying thread 1\n");
  1337. if( cmThreadIsValid(th2) )
  1338. if( cmThreadDestroy(&th2) != kOkThRC )
  1339. printf("Error destroying thread 1\n");
  1340. if( cmTs1p1cIsValid(q) )
  1341. if( cmTs1p1cDestroy(&q) != kOkThRC )
  1342. printf("Error destroying queue\n");
  1343. }
  1344. //============================================================================================================================/
  1345. //
  1346. // cmTsMp1cTest()
  1347. //
  1348. // param recd for use by _cmTsQueueCb0() and
  1349. // the msg record passed between the sender
  1350. // threads and the receiver thread
  1351. typedef struct
  1352. {
  1353. unsigned id;
  1354. cmTsMp1cH_t qH;
  1355. int val;
  1356. } _cmTsMp1cCbParam_t;
  1357. unsigned _cmTsMp1cVal = 0;
  1358. // Incr the global value _cmTsMp1cVal and put it in a TS queue
  1359. bool _cmTsMp1cCb0(void* param)
  1360. {
  1361. _cmTsMp1cCbParam_t* p = (_cmTsMp1cCbParam_t*)param;
  1362. //p->val = __sync_fetch_and_add(&_cmTsMp1cVal,1);
  1363. cmThUIntIncr(&_cmTsMp1cVal,1);
  1364. p->val = _cmTsMp1cVal;
  1365. // send the msg
  1366. if( cmTsMp1cEnqueueMsg( p->qH, p, sizeof(_cmTsMp1cCbParam_t)) == kOkThRC )
  1367. printf("in:%i %i\n",p->id,p->val);
  1368. else
  1369. printf("in error %i\n",p->id);
  1370. cmSleepUs(100*1000);
  1371. return true;
  1372. }
  1373. // Monitor a TS queue for incoming messages from _cmTsMp1cCb1()
  1374. bool _cmTsMp1cCb1(void* param)
  1375. {
  1376. // the thread param is a ptr to the TS queue to monitor.
  1377. cmTsMp1cH_t* qp = (cmTsMp1cH_t*)param;
  1378. cmThRC_t rc;
  1379. _cmTsMp1cCbParam_t msg;
  1380. // dequeue any waiting messages
  1381. if((rc = cmTsMp1cDequeueMsg( *qp, &msg, sizeof(msg))) == kOkThRC )
  1382. printf("out - cons id:%i val:%i\n",msg.id,msg.val);
  1383. else
  1384. {
  1385. if( rc != kBufEmptyThRC )
  1386. printf("out error:%i\n", rc);
  1387. }
  1388. return true;
  1389. }
  1390. // Test the TS queue by starting sender threads (threads 0 & 1)
  1391. // and a receiver thread (thread 2) and sending messages
  1392. // from the sender to the receiver.
  1393. void cmTsMp1cTest( cmRpt_t* rpt )
  1394. {
  1395. cmThreadH_t th0=cmThreadNullHandle,th1=cmThreadNullHandle,th2=cmThreadNullHandle;
  1396. cmTsMp1cH_t q=cmTsMp1cNullHandle;
  1397. _cmTsMp1cCbParam_t param0, param1;
  1398. // create a TS Queue
  1399. if( cmTsMp1cCreate(&q,1000,NULL,NULL,rpt) != kOkThRC )
  1400. goto errLabel;
  1401. // create thread 0 - producer 0
  1402. param0.id = 0;
  1403. param0.qH = q;
  1404. if( cmThreadCreate(&th0,_cmTsMp1cCb0,&param0,rpt) != kOkThRC )
  1405. goto errLabel;
  1406. // create thread 1 - producer 1
  1407. param1.id = 1;
  1408. param1.qH = q;
  1409. if( cmThreadCreate(&th1,_cmTsMp1cCb0,&param1,rpt) != kOkThRC )
  1410. goto errLabel;
  1411. // create thread 2 - consumer 0
  1412. if( cmThreadCreate(&th2,_cmTsMp1cCb1,&q,rpt) != kOkThRC )
  1413. goto errLabel;
  1414. // start thread 0
  1415. if( cmThreadPause(th0,0) != kOkThRC )
  1416. goto errLabel;
  1417. // start thread 1
  1418. if( cmThreadPause(th1,0) != kOkThRC )
  1419. goto errLabel;
  1420. // start thread 2
  1421. if( cmThreadPause(th2,0) != kOkThRC )
  1422. goto errLabel;
  1423. printf("any key to quit.");
  1424. getchar();
  1425. errLabel:
  1426. if( cmThreadIsValid(th0) )
  1427. if( cmThreadDestroy(&th0) != kOkThRC )
  1428. printf("Error destroying thread 0\n");
  1429. if( cmThreadIsValid(th1) )
  1430. if( cmThreadDestroy(&th1) != kOkThRC )
  1431. printf("Error destroying thread 1\n");
  1432. if( cmThreadIsValid(th2) )
  1433. if( cmThreadDestroy(&th2) != kOkThRC )
  1434. printf("Error destroying thread 1\n");
  1435. if( cmTsMp1cIsValid(q) )
  1436. if( cmTsMp1cDestroy(&q) != kOkThRC )
  1437. printf("Error destroying queue\n");
  1438. }
  1439. void cmSleepUs( unsigned microseconds )
  1440. { usleep(microseconds); }
  1441. void cmSleepMs( unsigned milliseconds )
  1442. { cmSleepUs(milliseconds*1000); }