C语言线程调度

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<semaphore.h>//信号量头文件
#define ARRAY_SIZE 1024
sem_t bin;//信号量
char values[ARRAY_SIZE];
void *func(void * message)
{
   sem_wait(&bin);//当信号量为0时等待,直到信号量大于1
   while(strncmp("end",values,3))
   {
   printf("your input str num is %d\n",strlen(values)-1);
   sem_wait(&bin);
   }
   pthread_exit(NULL);//线程结束
}
int main()
{
    pthread_t thread;
    int res;
    void * result;
    res=pthread_create(&thread,0,func,NULL);//创建一个线程,特性为默认特性,如果返回值不为0则出错。
    if(res)
    {
       perror("thred init error !\n");
       exit(EXIT_FAILURE);
    }
    printf("input your str,end by end\n");
    while(strncmp(values,"end",3))
    {
      fgets(values,ARRAY_SIZE,stdin);
      sem_post(&bin);//信号量增加1
    }
    printf("wait thread to end.............\n");
    if(pthread_join(thread,&result))//等待线程结束,如果返回值不为0则出错
    {
       perror("phtread join error !\n");
       exit(EXIT_FAILURE);
    }
    printf("join ok\n");
    sem_destroy(&bin);//销毁线程
    exit(EXIT_SUCCESS);
}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 C 语言中,线程是通过操作系统提供的线程库来实现的。线程可以让程序同时执行多个任务,从而提高程序的并发性和效率。 任务调度是指操作系统根据一定的策略将 CPU 的执行时间分配给不同的线程或进程。在 C 语言中,任务调度是由操作系统完成的,程序员只需要编写线程的代码,然后将线程交给操作系统进行调度。 通常情况下,线程调度是基于优先级的。操作系统会将 CPU 时间分配给具有最高优先级的线程,直到该线程完成或被阻塞。当该线程完成或被阻塞后,操作系统会选择下一个具有最高优先级的线程运行。如果没有线程处于运行状态,那么操作系统会将 CPU 时间分配给等待队列中的线程线程在 C 语言中的使用需要包含头文件 pthread.h,并使用 pthread_create() 函数创建线程,该函数会返回一个线程 ID,然后使用 pthread_join() 函数等待线程结束。 下面是一个简单的例子,它创建了两个线程并让它们同时执行: ``` #include <stdio.h> #include <pthread.h> void* thread_function(void* arg) { printf("Thread %d is running\n", *((int*)arg)); return NULL; } int main() { pthread_t thread1, thread2; int thread1_id = 1, thread2_id = 2; pthread_create(&thread1, NULL, thread_function, &thread1_id); pthread_create(&thread2, NULL, thread_function, &thread2_id); pthread_join(thread1, NULL); pthread_join(thread2, NULL); return 0; } ``` 在上面的例子中,我们首先定义了一个函数 thread_function(),它将作为线程的入口点。然后我们使用 pthread_create() 函数创建了两个线程,并将它们分别赋值给 thread1 和 thread2 变量。每个线程都将调用 thread_function() 函数,并传递一个整数参数作为线程 ID。最后,我们使用 pthread_join() 函数等待线程结束。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值