一个Linux下多线程Demo

来源:互联网 发布:js时间戳转换成日期 编辑:程序博客网 时间:2024/04/30 13:00

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <sys/socket.h>

#include <sys/types.h>

#include <sys/time.h>

#include <sys/ioctl.h>

#include <netinet/in.h>

#include <arpa/inet.h>

#include <net/if.h>

#include <unistd.h>

#include <fcntl.h>

#include <pthread.h>

#include <semaphore.h>

#include <netdb.h>

#include <ifaddrs.h>

#include <sys/socket.h>

#include <net/if.h>

typedef struct VideoHandler

{

    int recviceing;                 //接收数据标识

    int timeout;                    //超时时间

    pthread_t hThread;              //线程句柄

    pthread_mutex_t mutex;          //互斥量

    pthread_cond_t  cond;           //

}VideoHandler;

VideoHandler *pVideoHandler = NULL;


void *RecvThread(void *lpParameter) {

    //作为参数传入

    VideoHandler *pVideo = (VideoHandler*)lpParameter;

    int len;

    struct timespec timeoutTime;

    //加入互斥量

    pthread_mutex_lock(&pVideo->mutex);

    while(1 == pVideo->recviceing)

    {

        if (0 == pVideo->recviceing) {

            //Exit Thread............

            //线程退出标识

            break;

        }

        //len=recvfrom();

        if(len < 0)

        {

            continue;

        }

        //  其他处理.......

      

        //线程等待5

        timeoutTime.tv_sec = time(NULL) + pVideo->timeout;

        timeoutTime.tv_nsec = 0.0;

        pthread_cond_timedwait(&pVideo->cond, &pVideo->mutex, &timeoutTime);

    }

    //解除互斥量

    pthread_mutex_unlock(&pVideo->mutex);

    return ((void*)0); 

}

/*初始化变量,创建线程*/

int initVideoThread() {

    pVideoHandler = malloc(sizeof(VideoHandler));

    

    pthread_mutex_init(&pVideoHandler->mutex,NULL);

    pthread_cond_init(&pVideoHandler->cond,NULL);

    pVideoHandler->recviceing =1;

    pVideoHandler->timeout =5;

    pthread_create(&pVideoHandler->hThread,NULL,&RecvThread,(void *)&pVideoHandler);

    return 0;

}

/*释放线程*/

int freeVideoThread() {

    if (0 !=pVideoHandler->recviceing) {

        pVideoHandler->recviceing =0;

    }

    //等待直到线程退出

    pthread_join(pVideoHandler->hThread,NULL);

   free(pVideoHandler);

    return 0;

}

0 0
原创粉丝点击