C 与 多线程(1)

C 与 多线程(1)

我们可以用C编写多线程程序吗?

  • C 语言标准不支持多线程
  • POSIX Threads (or Pthreads) is a POSIX standard for threads.
  • gcc compiler 提供了一种 pthread 的实现

一个简单的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 Thread\n"); 
	pthread_create(&thread_id, NULL, myThreadFun, NULL); 
	pthread_join(thread_id, NULL); 
	printf("After Thread\n"); 
	exit(0); 
}

编译

要使用gcc编译多线程程序,我们需要将其与pthreads库链接。

gcc multithread.c -lpthread

运行

./a.out

多线程具有全局变量和静态变量

所有线程共享数据段全局变量静态变量存储在数据段中。因此,它们被所有线程共享。下面的示例程序进行了演示。

#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: %d\n", *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; 
} 

请注意,以上是显示线程如何工作的简单示例。在线程中访问全局变量通常不是一个好主意。如果线程2优先于线程1并且线程1需要更改变量,该怎么办。实际上,如果需要多个线程访问全局变量,则应使用互斥锁对其进行访问。

References:

原文:

  • https://www.geeksforgeeks.org/multithreading-c-2/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值