线程自动创建与销毁

#include <stdio.h>
#include <semaphore.h>
#include <pthread.h>
#include <fcntl.h>
#include <unistd.h>
 
 
#define filePath "/mnt/My/MutxThread/file.log"
sem_t sem_1, sem_2;
int num = 0;
 int fd = 0;
unsigned char *writeLog;
static int count = 5;
static pthread_t thread_flag = 0;
 
 
int *do_Thread_1(void *data)
{
    int ret;
    count = 5;
//    printf("%s: begin to write\n",__func__);
    while(1)
    {
        ret = write(fd, "123", 3);
        printf("%s:count = %d ret = %d\n", __func__,count, ret);
         sleep(1);
        count--;
        if(!count)
            pthread_exit(0);  
    }
}
 
void init_file()
{
    unsigned char i = 0;
    if(!access(filePath, F_OK))
    {
        fd = open(filePath, O_APPEND | O_RDWR, 0777);
        printf("%s:open file success\n",__func__);
    }
    else
    {
        fd = open(filePath, O_CREAT | O_RDWR, 0777);
        printf("%s: create file\n",__func__);
    }
    if(fd < 0)
    {
        printf("%s: open file failed\n",__func__);
    }
}
 
void create_thread()
{
    pthread_create(&thread_flag, NULL, do_Thread_1, NULL);
}
 
void close_file()
{
    printf("%s:",__func__);
    if(fd>0)
        close(fd);
    fd = 0;
}
 
void test_thread()
{
    int *ret;
retry:
    
    init_file();
    create_thread();

/**pthread_join()函数有自动销毁内存资源的功能,所以我们在退出线程,重新创建的时候不用考虑内存资源的问题**/

    pthread_join(thread_flag, &ret);

    close_file();
    goto retry;
    //while(1)  
    //    sleep(1);
}
 
void main()
{
    writeLog = "123456789";
    test_thread();
    
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值