吾爱程序员:这里有好玩的游戏和软件
当前位置:首页C语言教程 → C语言中的多线程

C语言中的多线程

来源:网络 | 更新时间:2022-02-04 09:31:34
什么是线程? 线程是进程中的单个序列流。因为线程具有进程的一些属性,所以它们有时被称为轻量级进程 进程和线程有什么区别? 线程不独立于其他类似进程,因此线程与其他线程共享它们的代码部分、数据部分和操作系统资源,如打开的文件和信号。但是,与进程一样,线程也有自己的程序计数器 (PC)、寄存器集和堆栈空间。 为什么是多线程? 线程是通过并行性改进应用程序的流行方式。例如,在浏览器中,多个选项卡可以是不同的线程。MS word 使用多个线程,一个线程格式化文本,另一个线程处理输入等。 由于以下原因,线程比进程运行得更快: 1)线程创建速度更快。 2)线程之间的上下文切换要快得多。 3)线程可以轻松终止 4)线程之间的通信更快。 有关详细信息,请参阅http://www.personal.kent.edu/~rmuhamma/OpSystems/Myos/threads.htm 。 我们可以用 C 编写多线程程序吗? 与 Java 不同,语言标准不支持多线程。POSIX 线程(或 Pthreads)是线程的 POSIX 标准。pthread 的实现可通过 gcc 编译器获得。 一个简单的 C 程序来演示 pthread 基本功能的使用 请注意,下面的程序只能用带有 pthread 库的 C 编译器编译。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> //Header file for sleep(). man 3 sleep for details.
#include <pthread.h>

// A normal C function that is executed as a thread 
// when its name is specified in pthread_create()
void *myThreadFun(void *vargp)
{
sleep(1);
printf("Printing GeeksQuiz from Thread n");
return NULL;
}

int main()
{
pthread_t thread_id;
printf("Before Threadn");
pthread_create(&thread_id, NULL, myThreadFun, NULL);
pthread_join(thread_id, NULL);
printf("After Threadn");
exit(0);
}
在 main() 中,我们声明了一个名为 thread_id 的变量,它的类型为 pthread_t,它是一个整数,用于标识系统中的线程。声明 thread_id 后,我们调用 pthread_create() 函数来创建线程。 pthread_create() 接受 4 个参数。 第一个参数是指向此函数设置的 thread_id 的指针。 第二个参数指定属性。如果值为 NULL,则应使用默认属性。 第三个参数是要为要创建的线程执行的函数的名称。 第四个参数用于将参数传递给函数 myThreadFun。 线程的 pthread_join() 函数等效于进程的 wait()。对 pthread_join 的调用会阻塞调用线程,直到标识符等于第一个参数的线程终止。 如何编译上面的程序? 要使用 gcc 编译多线程程序,我们需要将其与 pthreads 库链接。以下是用于编译程序的命令。
gfg@ubuntu:~/$ gcc multithread.c -lpthread
gfg@ubuntu:~/$ ./a.out
Before Thread
Printing GeeksQuiz from Thread 
After Thread
gfg@ubuntu:~/$
AC 程序显示具有全局变量和静态变量的多个线程 如上所述,所有线程共享数据段。全局变量和静态变量存储在数据段中。因此,它们由所有线程共享。下面的示例程序演示了相同的内容。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

// Let us create a global variable to change it in threads
int g = 0;

// The function to be executed by all threads
void *myThreadFun(void *vargp)
{
// Store the value argument passed to this thread
int *myid = (int *)vargp;

// Let us create a static variable to observe its changes
static int s = 0;

// Change static and global variables
++s; ++g;

// Print the argument, static and global variables
printf("Thread ID: %d, Static: %d, Global: %dn", *myid, ++s, ++g);
}

int main()
{
int i;
pthread_t tid;

// Let us create three threads
for (i = 0; i < 3; i++)
pthread_create(&tid, NULL, myThreadFun, (void *)&tid);

pthread_exit(NULL);
return 0;
}
gfg@ubuntu:~/$ gcc multithread.c -lpthread
gfg@ubuntu:~/$ ./a.out
Thread ID: 3, Static: 2, Global: 2
Thread ID: 3, Static: 4, Global: 4
Thread ID: 3, Static: 6, Global: 6
gfg@ubuntu:~/$
请注意,上面是显示线程如何工作的简单示例。在线程中访问全局变量通常是个坏主意。如果线程 2 的优先级高于线程 1 并且线程 1 需要更改变量怎么办。在实践中,如果需要多个线程访问全局变量,则应该使用互斥锁来访问它们。

最新文章

热点资讯

手游排行榜

CopyRight 2020-2030吾爱程序员

鄂ICP备2021004581号-8

本站资源收集于网络,如有侵权请联系我们:35492删除0109@qq.com