求哪位好心人,把这个改成一个线程负责打印,一个线程负责定时,1秒到了,终止打印,看总共打印了多少行

cxdzxc 2012-06-29 05:41:08
#include <stdio.h>
#include <Windows.h>
#include <time.h>
#include <process.h>

unsigned __stdcall Print(void *params)
{
int i = 0;
clock_t start;
start = clock();
while ((double)(clock() - start) / CLOCKS_PER_SEC < 1.0)
{
printf("%d\n", ++i);
}
return 0;
}

int main()
{
HANDLE hThread;
unsigned threadId;
hThread = (HANDLE)_beginthreadex(NULL, 0, &Print, NULL, 0, &threadId);
WaitForSingleObject(hThread, INFINITE);
CloseHandle(hThread);
system("pause");
}
...全文
166 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
cxdzxc 2012-06-30
  • 打赏
  • 举报
回复
搞个完整的,增加头文件和暂停:
#include <stdio.h>
#include <Windows.h>
#include <time.h>
#include <process.h>

volatile LONG g_bCon;

void printThread(void* pArg)
{
int i = 0;
while(g_bCon)
{
printf("%d\n",i++);
}
}

void countThread(void* pArg)
{
_beginthread(printThread,0,0);
Sleep(1000);
g_bCon = 0;
}

int main(int argc, char* argv[])
{
g_bCon = 1;
_beginthread(countThread,0,0);
system("pause"); /*这里必须要暂停下*/
return 0;
}
cxdzxc 2012-06-29
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 的回复:]

C/C++ code

volatile LONG g_bCon;

void printThread(void* pArg)
{
int i = 0;
while(g_bCon){
printf("%d\n",i++);
}
}

void countThread(void* pArg)
{
_beginthread(printThread,0……
[/Quote]
此方法堪称经典,让我瞬间多线程入门了,非常之感谢,求大神联系方式,我的是750347821@QQ.com
beckhanyan 2012-06-29
  • 打赏
  • 举报
回复
另外。。。_beginthread创建的线程无需调用CloseHandle
youkuxiaobin 2012-06-29
  • 打赏
  • 举报
回复

#include <stdio.h>
#include <Windows.h>
#include <time.h>
#include <process.h>
int g_start = -1;
unsigned __stdcall Print(void *params)
{
int i = 0;
clock_t start;
start = clock();
while(g_start == -1)
sleep(1);
while (g_start == 0) / CLOCKS_PER_SEC < 1.0)
{
printf("%d\n", ++i);
}
return 0;
}

unsigned __stdcall Control(void *params)
{
int i = 0;
clock_t start;
start = clock();
g_start == 0;
sleep(1000);
g_start ==-1
return 0;
}
int main()
{
HANDLE hThread;
unsigned threadId;
hThread = (HANDLE)_beginthreadex(NULL, 0, &Print, NULL, 0, &threadId);

HANDLE hThread1;
unsigned threadId1;
hThread1 = (HANDLE)_beginthreadex(NULL, 0, &Control, NULL, 0, &threadId1);
WaitForSingleObject(hThread, INFINITE);
WaitForSingleObject(hThread1, INFINITE);
CloseHandle(hThread);
CloseHandle(hThread1);
system("pause");
}

太精准了还是做不到,这个是不使用互斥量的也可以

beckhanyan 2012-06-29
  • 打赏
  • 举报
回复

volatile LONG g_bCon;

void printThread(void* pArg)
{
int i = 0;
while(g_bCon){
printf("%d\n",i++);
}
}

void countThread(void* pArg)
{
_beginthread(printThread,0,0);
Sleep(1000);
g_bCon = 0;
}

int main(int argc, char* argv[])
{
g_bCon = 1;
_beginthread(countThread,0,0);
return 0;
}
cxdzxc 2012-06-29
  • 打赏
  • 举报
回复
追加到100分,希望有大虾来答下

69,370

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧