linux 线程 例程(使用方法)

01 #include <stdio.h>
02 #include <pthread.h>
03 #include <stdlib.h>
04 #include <sched.h>    //sched_setscheduler()
05
06 void thread(void)
07 {
08     int i;
09 
10     struct sched_param param;
11 
12     sched_getparam(0, &param);
13     printf("priority = %d\n", param.sched_priority);
14     printf("policy = %d\n", sched_getscheduler(0));
15 
16     param.sched_priority = 99;  // 99 is 最高优先级
17
18     sched_setscheduler(0, SCHED_FIFO, &param);
19     for (i = 0; i < 3; i++)
20         printf("This is a pthread.\n");
21 }   
22     
23 int main(void)
24 {   
25     pthread_t id;
26     int i, ret;
27     ret = pthread_create(&id, NULL, (void *)thread, NULL);
28     if (ret != 0)
29     {
30         printf("Create pthread error!\n");
31         exit(1);
32     }
33
34     return(0);
35 }

gcc test.c -lpthread




#include <stdio.h>
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <sched.h>    //sched_setscheduler()


pthread_mutex_t mutex;
int g_max;

void thread(void)
{
    int i;

    //struct sched_param param;

    //sched_getparam(0, &param);
    //printf("priority = %d\n", param.sched_priority);
    //printf("policy = %d\n", sched_getscheduler(0));

    //param.sched_priority = 99;  // 99 is 最高优先级

    //sched_setscheduler(0, SCHED_FIFO, &param);
    //for (i = 0; i < 3; i++)
    //    printf("This is a pthread.\n");
    
    pthread_mutex_lock(&mutex);   // 获取互斥锁
    g_max = 100;
    pthread_mutex_unlock(&mutex); // 释放互斥锁
    
    while (1)
    {
        sleep (1);
        printf ("%s %d\n", __FUNCTION__, __LINE__);
    }
    //pthread_exit(0);
}   

int main(void)
{   
    pthread_t id;
    int i, ret;
    pthread_mutex_init(&mutex, NULL); // 创建互斥锁
    ret = pthread_create(&id, NULL, (void *)thread, NULL); // 创建线程
    if (ret != 0)
    {
        printf("Create pthread error!\n");
        exit(1);
    }

    for (i = 0; i < 3; i++)
    {
        sleep(1);
        printf ("%s %d i = %d\n", __FUNCTION__, __LINE__, i);
    }
    pthread_mutex_destroy(&mutex);  // 销毁互斥锁

    pthread_cancel (id);  // 销毁线程
    printf ("%s %d\n", __FUNCTION__, __LINE__);
    
    return(0);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值