Відмінності між версіями «Тема 13. Моделювання станів процесів в Windows»

Матеріал з Вікі ЦДУ
Перейти до: навігація, пошук
Рядок 3: Рядок 3:
 
=new=
 
=new=
 
  //Closing the handle before the thread procedure returns
 
  //Closing the handle before the thread procedure returns
//I have heard of this being done, although this page doesn't seem to mention if it's valid to do such a thing. I've even heard of those that call CloseHandle() on the thread handle immediately after creating the thread. So what's the deal here?Yes, you can close the thread handle immediately, the thread object will exist until all handles are closed and the thread has terminated. Closing the handles before the thread terminates isn't explicitely allowed here - but also not explicitely forbidden, and numerous samples make use of these "one-shot threads". (ph)
+
//I have heard of this being done, although this page doesn't seem to mention if it's valid to do such a thing. I've even heard of those that call CloseHandle() on the thread handle immediately after creating the thread. So what's the deal here?Yes, you can close the thread handle immediately, the thread object will exist until all handles are closed and the thread has terminated. Closing the handles before the thread terminates isn't explicitely allowed here - but also not explicitely forbidden, and numerous samples make use of these "one-shot threads". (ph)
#include <windows.h>
+
#include <windows.h>
#include <stdio.h>
+
#include <stdio.h>
#include <stdlib.h>
+
#include <stdlib.h>
  
DWORD ThreadProc (LPVOID lpdwThreadParam );
+
DWORD ThreadProc (LPVOID lpdwThreadParam );
  
//Global variable Shared by all threads
+
//Global variable Shared by all threads
int nGlobalCount = 0;
+
int nGlobalCount = 0;
//Main function which starts out each thread
+
//Main function which starts out each thread
int __cdecl main( int argc, char **argv)
+
int __cdecl main( int argc, char **argv)
{  
+
{  
int i, nThreads = 5;
+
int i, nThreads = 5;
DWORD dwThreadId;
+
DWORD dwThreadId;
//Determine the number of threads to start
+
//Determine the number of threads to start
if (argc > 1) {
+
if (argc > 1) {
nThreads = atoi( argv[1]);
+
nThreads = atoi( argv[1]);
}
+
}
  
 
//Set the global count to number of threads
 
//Set the global count to number of threads

Версія за 20:11, 13 грудня 2013

Ця стаття допоможе студентам при виконанні даної лабораторної роботи. Стаття написана з власного досвіду. Сьогодні ми будемо моделювати стани процесів в Windows з допомогою мови програмування С++ - всього їх розглянемо 5. Нам знадобляться Dev-C++ для компіляції програм і ProcessHacker для їх моніторингу. Рядки вихідного коду програм мають нумерацію, що дозволить давати коментарі щодо загальних принципів роботи програм. Ці коментарі знаходятся у тому ж розділі статті, що і відповідний лістинг. На початку коментаря в дужках вказано номер рядка, до якого цей коментар стосується. У ProcessHacker різні типи потоків підсвічуються різними кольорами - якому кольору відповідає який тип, можна з"ясувати в налаштуваннях програми. Отже, до справи!

new

//Closing the handle before the thread procedure returns
//I have heard of this being done, although this page doesn't seem to mention if it's valid to do such a thing. I've even heard of those that call CloseHandle() on the thread handle immediately after creating the thread. So what's the deal here?Yes, you can close the thread handle immediately, the thread object will exist until all handles are closed and the thread has terminated. Closing the handles before the thread terminates isn't explicitely allowed here - but also not explicitely forbidden, and numerous samples make use of these "one-shot threads". (ph)
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
DWORD ThreadProc (LPVOID lpdwThreadParam );
//Global variable Shared by all threads
int nGlobalCount = 0;
//Main function which starts out each thread
int __cdecl main( int argc, char **argv)
{ 
int i, nThreads = 5;
DWORD dwThreadId;
//Determine the number of threads to start
if (argc > 1) {
nThreads = atoi( argv[1]);
}

//Set the global count to number of threads nGlobalCount = nThreads; //Start the threads for (i=1; i<= nThreads; i++) { //printf("i - %d\n",i); if (CreateThread(NULL, //Choose default security 0, //Default stack size (LPTHREAD_START_ROUTINE)&ThreadProc, //Routine to execute (LPVOID) &i, //Thread parameter 0, //Immediately run the thread &dwThreadId //Thread Id ) == NULL) { printf("Error Creating Thread#: %d\n",i); return(1); } else { printf("Global Thread Count: %d %d %d\n", nGlobalCount, nThreads, i); Sleep(1000); } } return 0; }

//Thread Routine DWORD ThreadProc (LPVOID lpdwThreadParam ) { //Print Thread Number printf ("Thread #: %d\n", *((int*)lpdwThreadParam)); //Reduce the count nGlobalCount--; //ENd of thread return 0; }

ready

//This function causes a thread to relinquish the remainder of its time slice and become unrunnable for an interval based on the value of dwMilliseconds. The system clock "ticks" at a constant rate. If dwMilliseconds is less than the resolution of the system clock, the thread may sleep for less than the specified length of time. If dwMilliseconds is greater than one tick but less than two, the wait can be anywhere between one and two ticks, and so on. To increase the accuracy of the sleep interval, call the timeGetDevCaps function to determine the supported minimum timer resolution and the timeBeginPeriod function to set the timer resolution to its minimum. Use caution when calling timeBeginPeriod, as frequent calls can significantly affect the system clock, system power usage, and the scheduler. If you call timeBeginPeriod, call it one time early in the application and be sure to call the timeEndPeriod function at the very end of the application.

//After the sleep interval has passed, the thread is ready to run. If you specify 0 milliseconds, the thread will relinquish the remainder of its time slice but remain ready. Note that a ready thread is not guaranteed to run immediately. Consequently, the thread may not run until some time after the sleep interval elapses.

  1. include <iostream>
  1. include <windows.h>

int main ()

{

   std::cout << "Message 1\n" ;
   Sleep(2000);                     // number is in milliseconds 1Sec = 1000 MiliSeconds
   std::cout << "Message 2 a two seconds after Message 1" ;
  return 0;

}

running

#include <time.h>
  1. include <conio.h>
  2. include <iostream>
  3. include <string>
  4. include <windows.h>
  5. define timer 5.0

using namespace std; int main() { double dif=0; while(1) { dif+=1; } getch(); return 0; }

terminated

//To make the Console wait for 't' seconds for an input

//This program has a countdown timer. After the countdown gets over, the input session starts.

  1. include <time.h>
  2. include <conio.h>
  3. include <iostream>
  4. include <string>
  5. include <windows.h>
  6. define timer 5.0

using namespace std; int main() { double dif=0; time_t start,end; time(&start); string s; while(dif<timer) //Countdown before starting { printf("Type a word after %.0lf seconds..\nYour Time starts in..\n",timer); time (&end); dif = difftime(end,start); printf( "%.0lf seconds\n", timer-dif); Sleep(1000); system("CLS"); } HANDLE h_to_console=GetStdHandle( STD_INPUT_HANDLE ); FlushConsoleInputBuffer(h_to_console); cout<<"Enter the String:\n"; cin>>s; cout<<"You have Entered: "<<s; getch(); return 0; }

waiting

  1. include <time.h>
  2. include <conio.h>
  3. include <iostream>
  4. include <string>
  5. include <windows.h>
  6. define timer 5.0

using namespace std; int main() {

string s;

cout<<"Enter the String:\n"; cin>>s; cout<<"You have Entered: "<<s; getch(); return 0; }