C语言中如何进行线程和进程操作?

C语言在操作系统中提供了一些库函数,可以方便地进行进程和线程的操作。

进程操作

创建新进程

使用 fork() 函数可以在当前进程中创建一个新进程。新进程继承了父进程的所有属性,但是父进程和子进程拥有独立的内存空间。下面是一个示例:

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>

int main() {
    pid_t pid;
    pid = fork();
    if (pid < 0) { // fork失败
        perror("fork error");
    } else if (pid == 0) { // 子进程
        printf("I'm child process with pid %d\n", getpid());
    } else { // 父进程
        printf("I'm parent process with pid %d, my child's pid is %d\n", getpid(), pid);
    }
    return 0;
}

上述代码中,我们使用了 fork() 函数创建了一个新进程。父进程和子进程的 pid 是不同的,可以通过 getpid() 函数获取当前进程的 pid。运行代码,输出如下:

I'm parent process with pid 6249, my child's pid is 6250
I'm child process with pid 6250

等待进程结束

使用 waitpid() 函数可以等待进程结束。下面是一个示例:

#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>

int main() {
    pid_t pid;
    pid = fork();
    if (pid < 0) { // fork失败
        perror("fork error");
    } else if (pid == 0) { // 子进程
        printf("I'm child process with pid %d\n", getpid());
        sleep(3);
    } else { // 父进程
        printf("I'm parent process with pid %d, my child's pid is %d\n", getpid(), pid);
        int status;
        waitpid(pid, &status, 0);
        printf("child process exited with status %d\n", status);
    }
    return 0;
}

上述代码中,父进程等待子进程结束,并且可以获取子进程的结束状态。运行代码,输出如下:

I'm parent process with pid 6265, my child's pid is 6266
I'm child process with pid 6266
child process exited with status 0

线程操作

使用 pthread_create() 函数可以创建新线程。新线程和主线程运行在同一个进程中,共享内存空间,但是有各自独立的栈空间。下面是一个示例:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void * print_hello(void * arg) {
    printf("hello from thread %ld\n", (long)arg);
    pthread_exit(NULL);
}

int main() {
    pthread_t tid;
    int rc = pthread_create(&tid, NULL, print_hello, (void *)1);
    if (rc) {
        perror("pthread_create error");
        exit(1);
    } else {
        printf("hello from main thread\n");
    }
    pthread_join(tid, NULL);
    return 0;
}

上述代码中,我们使用 pthread_create() 函数创建了一个新线程,新线程执行了 print_hello() 函数。主线程继续执行,输出了一行信息。 pthread_join() 函数等待线程结束。运行代码,输出如下:

hello from main thread
hello from thread 1

线程间同步

使用 pthread_mutex_lock()pthread_mutex_unlock() 函数可以实现线程间同步。下面是一个示例:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

int counter;
pthread_mutex_t mutex;

void * increment(void * arg) {
    int i;
    for (i = 0; i < 1000000; i++) {
        pthread_mutex_lock(&mutex);
        counter++;
        pthread_mutex_unlock(&mutex);
    }
    pthread_exit(NULL);
}

int main() {
    pthread_t t1, t2;
    pthread_mutex_init(&mutex, NULL);
    pthread_create(&t1, NULL, increment, NULL);
    pthread_create(&t2, NULL, increment, NULL);
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    pthread_mutex_destroy(&mutex);
    printf("counter = %d\n", counter);
    return 0;
}

上述代码中,我们使用了 pthread_mutex_lock()pthread_mutex_unlock() 函数来保证 counter 的值能够正确地被多个线程修改。 pthread_mutex_init()pthread_mutex_destroy() 分别用来初始化和销毁互斥锁。运行代码,输出如下:

counter = 2000000

总结

本文介绍了C语言中如何进行进程和线程操作。对于进程,我们使用 fork() 函数创建新进程,使用 waitpid() 函数等待进程结束。对于线程,我们使用 pthread_create() 函数创建新线程,使用 pthread_mutex_lock()pthread_mutex_unlock() 函数实现线程间同步。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:C语言中如何进行线程和进程操作? - Python技术站

(0)
上一篇 2023年4月27日
下一篇 2023年4月27日

相关文章

  • C语言字符串函数模拟实现流程介绍

    C语言字符串函数模拟实现是对字符串处理非常关键的一部分,理解其实现的流程和思路对于掌握C语言的字符串处理技巧非常有用。本攻略将为大家介绍C语言常用的字符串函数模拟实现的流程和相关要点。 一、字符串长度计算函数strlen模拟实现 字符串长度计算是字符串处理的基础操作之一,其系统函数为strlen。C语言中的strlen函数的作用是计算一个字符串的长度,即从该…

    C 2023年5月23日
    00
  • 详解C#对XML、JSON等格式的解析

    详解C#对XML、JSON等格式的解析 XML解析 在C#中,可以通过System.Xml命名空间下的类库实现对XML格式的解析。主要的类包括: XmlDocument:表示一个XML文档,可以通过该类的实例对象进行读取、创建、编辑XML文档。 XmlNode:表示XML文档中的一个节点。 XmlElement:表示XML文档中的一个元素节点。 XmlAtt…

    C 2023年5月23日
    00
  • C语言中如何判断质数

    C语言中判断一个数是否为质数的方法有很多种,下面是一种常见的方法: 1.定义一个变量i,从2开始逐个检查比该数小的自然数; 2.检查这些自然数中有没有能够整除该数的,若有则该数不是质数,反之则该数是质数; 3.循环结束后,若没有发现能够整除该数的自然数,则该数是质数。 下面是示例代码: #include <stdio.h> int isPrime…

    C 2023年5月23日
    00
  • c++11 chrono全面解析(最高可达纳秒级别的精度)

    C++11 Chrono全面解析 C++11出现了一组新的时间库——Chrono,可以方便进行时间戳计算和时间间隔计算,最高精度可达纳秒级别,比操作系统的时间函数更准确。 Chrono的基本元素 duration:表示一段时间的长度,由数值和时间单位组成,例如 std::chrono::duration<int, std::ratio<1, 10…

    C 2023年5月23日
    00
  • 详解C++11中的lambda匿名函数

    关于“详解C++11中的lambda匿名函数”的完整攻略,我将分以下几个方面展开: 一、什么是lambda表达式? lambda表达式是C++11标准中引入的新特性,它是一个匿名函数,可以在需要函数的地方直接定义函数并执行。 通常情况下,函数都需要在定义后才能被调用,而lambda表达式可以直接定义后立即执行。它非常方便,在一些场景下(如STL算法、函数式编…

    C 2023年5月23日
    00
  • linux c程序中获取shell脚本输出的实现方法

    获取shell脚本输出是Linux C编程中的一个常见需求,通常的实现方法是通过调用Linux系统的管道机制来实现。下面是具体的攻略: 步骤1:运行shell脚本并将输出写入到管道中 代码示例: $ echo "hello world" > /tmp/output.txt 上述示例向文件output.txt中写入了一行文本。要将其写…

    C 2023年5月30日
    00
  • C语言学生成绩管理系统课程设计word版

    针对“C语言学生成绩管理系统课程设计word版”的完整攻略,我将从以下几个方面进行讲解: 1.系统需求分析2.系统设计方案3.系统开发实现4.系统测试与维护 1.系统需求分析 在进行任何系统开发之前,必须清楚自己的需求,包括用户的需求和技术的需求,了解系统功能、数据存储和处理方式、用户交互等方面的要求。对于此次课程设计,针对学生成绩管理系统,我们需要考虑以下…

    C 2023年5月22日
    00
  • 详解C++中动态内存管理和泛型编程

    详解C++中动态内存管理和泛型编程 动态内存管理 何为动态内存 C++中的动态内存是指程序在运行时临时申请的内存空间,用于存储动态数据(变量)。 动态内存的申请和释放 C++中动态内存的申请是通过new操作符来实现的,申请成功后会返回一个指向该内存空间的指针;而该内存空间的释放则需要使用delete操作符。 // 动态申请内存 int* p = new in…

    C 2023年5月22日
    00
合作推广
合作推广
分享本页
返回顶部