C之多线程(例子很不错)
1.线程
- 线程池是一个树状结构。
- 多线程解决并发问题。
- 一个线程内部的执行顺序是线性的。而线程之间是乱序的。
- 若要创建一个多线程程序,它的参数必须是空指针类型。
- 变色龙程序:
-
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include <stdlib.h> #include <Windows.h> #include<process.h>//进程 #include <time.h> void timeset(void*p)//线程的main { int i = 0; while (1) { i++; char str[100] = { 0 }; sprintf(str, "title 当前时间第%d秒", i); system(str);//执行指令 Sleep(1000);//休眠1000毫秒 } system("color 3f"); } //多线程,调用其他函数也是一样 void go() { int num1 = (rand() % 16); Sleep(10); int num2 = rand() % 16; char str[50] = { 0 }; sprintf(str, "color %x%x", num1, num2); system(str); go(); } void colorall(void *p) { time_t ts; unsigned int num = time(&ts);//初始化时间种子 srand(num); go(); //for (;;) // { // int num1 = rand() % 16; // Sleep(10); // int num2 = rand() % 16; // char str[50] = { 0 }; // sprintf(str, "color %x%x", num1, num2); // system(str); // } //do //{ // int num1 = (rand() % 16); // Sleep(10); // int num2 = rand() % 16; // char str[50] = { 0 }; // sprintf(str, "color %x%x", num1, num2); // system(str); //} while (1); //AAA: // { // int num1 = (rand() % 16); // Sleep(10); // int num2 = rand() % 16; // char str[50] = { 0 }; // sprintf(str, "color %x%x", num1, num2); // system(str); // } // goto AAA; } void main() { _beginthread(timeset, 0, NULL); _beginthread(colorall, 0, NULL); //system("color 3f"); system("pause"); }
人怂胆子小,手拿大刀跑。