实现c语言多线程计算,如何用C语言实现多线程

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼

Windows操作系统,C语言实现多线程:

#include 

#include 

DWORD APIENTRY ThreadOne ( LPVOID threadArg )

{

printf ( "线程开始啦,参数是:%s\n" , (char *)threadArg );

return 0;

}

int main ( void )

{

HANDLE hThread;  /* 记录线程句柄 */

DWORD ThreadID;  /* 记录线程ID号 */

DWORD waitingResult;  /* 等待线程退出的等待结果 */

DWORD threadExitCode;  /* 记录线程的返回值 */

char * aMessage = "这是线程的参数" ;

/* 创建并启动线程ThreadOne,返回值为线程句柄,赋值给hThread */

hThread = CreateThread ( NULL, 0L, ThreadOne, (LPVOID)aMessage, 0L, &ThreadID );

if ( hThread == NULL )

{

printf ("线程ThreadOne创建失败。错误代码:%lu\n", GetLastError() );

return EXIT_FAILURE ;

}

/* 等待线程句柄为的hThread线程结束 */

waitingResult = WaitForSingleObject ( hThread, INFINITE );

if ( waitingResult == WAIT_FAILED )

{

printf ( "等待线程退出等待失败。错误代码:%lu\n" , GetLastError() ) ;

return EXIT_FAILURE ;

}

if ( GetExitCodeThread ( hThread , &threadExitCode ) )

printf ( "线程的返回值是%lu\n", threadExitCode ) ;

else

printf ( "获取线程的返回值获取失败。错误代码:%lu\n" , GetLastError() ) ;

return EXIT_SUCCESS ;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用C语言多线程计算30000000-30001000之间的质数的示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <pthread.h> #define NUM_THREADS 4 #define RANGE_START 30000000 #define RANGE_END 30001000 // 定义线程参数结构体 typedef struct { int start; int end; int *count; } thread_args; // 判断一个数是否为质数 int is_prime(int num) { int i; if (num <= 1) { return 0; } for (i = 2; i*i <= num; i++) { if (num % i == 0) { return 0; } } return 1; } // 线程函数 void *thread_func(void *args) { int i, count = 0; thread_args *thread_args = (thread_args *)args; for (i = thread_args->start; i <= thread_args->end; i++) { if (is_prime(i)) { count++; } } *(thread_args->count) += count; pthread_exit(NULL); } int main() { int i, count = 0; pthread_t threads[NUM_THREADS]; thread_args args[NUM_THREADS]; // 分配线程任务 for (i = 0; i < NUM_THREADS; i++) { args[i].start = RANGE_START + i*(RANGE_END-RANGE_START)/NUM_THREADS; args[i].end = RANGE_START + (i+1)*(RANGE_END-RANGE_START)/NUM_THREADS - 1; args[i].count = &count; pthread_create(&threads[i], NULL, thread_func, (void *)&args[i]); } // 等待线程结束 for (i = 0; i < NUM_THREADS; i++) { pthread_join(threads[i], NULL); } printf("Number of primes between %d and %d is %d\n", RANGE_START, RANGE_END, count); return 0; } ``` 代码中使用了4个线程来计算,可以根据需要调整`NUM_THREADS`的。线程函数`thread_func`中计算每个线程分配到的范围内的质数数量,并将结果累加到`count`变量中。最终输出计算结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值