- 论坛徽章:
- 0
|
一开始考虑错了,绕了点弯路,怎么都有问题,郁闷。晚上看着小说,福灵心至,分分钟写完,心情舒畅。
- #include <stdio.h>
- #include <pthread.h>
- #define MAX_NAME 255
- #define MAX_BUFF 4096
- typedef struct _TH_FILE {
- char Name[MAX_NAME];
- pthread_mutex_t mutex;
- struct _TH_FILE * pNext;
- } TH_FILE, * PTH_FILE;
- TH_FILE thFiles[4] = { 0 };
- typedef struct _TH_CONTS {
- char Conts[MAX_BUFF];
- } TH_CONTS, * PTH_CONTS;
- TH_CONTS thConts[4] = { 0 };
- void * thWriter( void * pParas ) {
- unsigned int nIdx = (unsigned int)pParas;
- PTH_FILE pFile = &thFiles[nIdx], pTmp;
- const char * pConts = thConts[nIdx].Conts;
- FILE * fp = NULL;
-
- while( 1 ) {
- pthread_mutex_lock( &(pFile->mutex) );
-
- // For testing
- /*
- switch( nIdx ) {
- case 0:
- usleep( 17 );
- break;
- case 1:
- usleep( 5 );
- break;
- case 2:
- usleep( 182 );
- break;
- case 3:
- usleep( 93 );
- break;
- }
- */
-
- if( ( fp = fopen( pFile->Name, "ab+" ) ) != NULL ) {
- fwrite( pConts, sizeof( char ), strlen( pConts ), fp );
- fclose( fp );
- }
-
- pTmp = pFile;
- pFile = pFile->pNext;
- pthread_mutex_unlock( &(pTmp->mutex) );
- }
-
- return( NULL );
- }
- int main( void ) {
- pthread_attr_t thAttr = { 0 };
-
- strcpy( (char *)&(thFiles[0].Name), "/tmp/A" );
- strcpy( (char *)&(thFiles[1].Name), "/tmp/B" );
- strcpy( (char *)&(thFiles[2].Name), "/tmp/C" );
- strcpy( (char *)&(thFiles[3].Name), "/tmp/D" );
- /*
- * "1": ADCBA...
- * "2": BADCB...
- * "3": CBADC...
- * "4": DCBAD...
- */
- thFiles[0].pNext = &thFiles[3]; // 写"1 ",线程写完A后写D
- thFiles[1].pNext = &thFiles[0]; // 写"2 ",线程写完B后写A
- thFiles[2].pNext = &thFiles[1]; // 写"3 ",线程写完C后写B
- thFiles[3].pNext = &thFiles[2]; // 写"4 ",线程写完D后写C
- pthread_mutex_init( &(thFiles[0].mutex), NULL );
- pthread_mutex_init( &(thFiles[1].mutex), NULL );
- pthread_mutex_init( &(thFiles[2].mutex), NULL );
- pthread_mutex_init( &(thFiles[3].mutex), NULL );
- memcpy( &(thConts[0].Conts), "1 ", strlen( "1 " ) );
- memcpy( &(thConts[1].Conts), "2 ", strlen( "2 " ) );
- memcpy( &(thConts[2].Conts), "3 ", strlen( "3 " ) );
- memcpy( &(thConts[3].Conts), "4 ", strlen( "4 " ) );
- pthread_attr_init( &thAttr );
- pthread_attr_setdetachstate( &thAttr, PTHREAD_CREATE_DETACHED );
-
- pthread_t tid = 0;
- pthread_create( &tid, &thAttr, thWriter, (void *)(0) );
- pthread_create( &tid, &thAttr, thWriter, (void *)(1) );
- pthread_create( &tid, &thAttr, thWriter, (void *)(2) );
- pthread_create( &tid, &thAttr, thWriter, (void *)(3) );
- pthread_attr_destroy( &thAttr );
-
- while( 1 ) {
- sleep( 10000 );
- }
-
- return( 0 );
- }
复制代码 |
|