libcm is a C development framework with an emphasis on audio signal processing applications.
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

cmThread.c 44KB

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