Thread library in windows

pthread.h в Visual Studio

Установка библиотеки pthread.h в среде Visual Studio

Н а примере Visual Studio 2012 Express Edition, Windows 7. Воспользуемся ресурсом ftp://sourceware.org/pub/pthreads-win32/dll-latest

  • 1. Скачайте все заголовочные *.h файлы из папки include и поместите их в папку include среды Visual Studio.
    Папка располагается примерно по такому адресу C:\Program Files\Microsoft Visual Studio 12.0\VC\include
  • 2. На ftp сервере перейдите в папку bin, далее в папку с подходящей архитектурой. Скопируйте в папку bin студии файл pthreadVSE2.dll.
    У меня эта папка располагается по адресу C:\Program Files\Microsoft Visual Studio 12.0\VC\bin
  • 3. Перейдите в папку lib, далее в папку с вашей архитектурой. Скопируйте файл pthreadVSE2.lib в папку lib студии.
    У меня она располагается по адресу C:\Program Files\Microsoft Visual Studio 12.0\VC\lib

Теперь появится возможность добавлять библиотеку pthread.h: Visual Studio увидит её, будет подсвечивать синтаксис и выводить подсказки.

  • 4. Создайте пустой проект. Откройте окно «Свойства проекта». Для этого либо кликните правой кнопкой мыши по имени проекта в Обозревателе решений | Свойства , либо откройте Проект | Свойства .
    Во вкладке Свойства конфигурации | Компоновщик | Ввод добавьте справа в дополнительные зависимости имя библиотеки pthreadVSE2.lib.

Добавление дополнительных зависимостей в проект с использованием библиотеки pthread.h

Каждый новый проект потребует этого шага. Для проверки напишем простое приложение

Вместо pthreadVSE2 можно качать и устанавливать файлы pthreadVC2. Но тогда и в дополнительных зависимостях придётся писать pthreadVC2.lib.

Creating Threads

The CreateThread function creates a new thread for a process. The creating thread must specify the starting address of the code that the new thread is to execute. Typically, the starting address is the name of a function defined in the program code (for more information, see ThreadProc). This function takes a single parameter and returns a DWORD value. A process can have multiple threads simultaneously executing the same function.

The following is a simple example that demonstrates how to create a new thread that executes the locally defined function, MyThreadFunction .

The calling thread uses the WaitForMultipleObjects function to persist until all worker threads have terminated. The calling thread blocks while it is waiting; to continue processing, a calling thread would use WaitForSingleObject and wait for each worker thread to signal its wait object. Note that if you were to close the handle to a worker thread before it terminated, this does not terminate the worker thread. However, the handle will be unavailable for use in subsequent function calls.

The MyThreadFunction function avoids the use of the C run-time library (CRT), as many of its functions are not thread-safe, particularly if you are not using the multithreaded CRT. If you would like to use the CRT in a ThreadProc function, use the _beginthreadex function instead.

It is risky to pass the address of a local variable if the creating thread exits before the new thread, because the pointer becomes invalid. Instead, either pass a pointer to dynamically allocated memory or make the creating thread wait for the new thread to terminate. Data can also be passed from the creating thread to the new thread using global variables. With global variables, it is usually necessary to synchronize access by multiple threads. For more information about synchronization, see Synchronizing Execution of Multiple Threads.

The creating thread can use the arguments to CreateThread to specify the following:

  • The security attributes for the handle to the new thread. These security attributes include an inheritance flag that determines whether the handle can be inherited by child processes. The security attributes also include a security descriptor, which the system uses to perform access checks on all subsequent uses of the thread’s handle before access is granted.
  • The initial stack size of the new thread. The thread’s stack is allocated automatically in the memory space of the process; the system increases the stack as needed and frees it when the thread terminates. For more information, see Thread Stack Size.
  • A creation flag that enables you to create the thread in a suspended state. When suspended, the thread does not run until the ResumeThread function is called.
Читайте также:  Java patch windows 10

You can also create a thread by calling the CreateRemoteThread function. This function is used by debugger processes to create a thread that runs in the address space of the process being debugged.

How do I install pthread_win32 (Windows pthread / posix thread library) for Visual Studio 2005?

Just to be clear — I have searched the depths of the internet and back for information on how to do this

I’m looking for assistance setting up pthread_Win32 to work with Visual Studio 2005. I’m programming in C, and I have a number of multithreaded assignments to write using pthread.h. However, since pthread is native to unix, I have to write all of my code, ftp it, and then ssh to my class’ remote unix system to run it. It makes development take so much longer, and it’s incredibly inefficient. I’d love (more than anything) to be able to get this working on my win32 machine, so I can develop in visual studio as I’ve been doing for quite some time.

I’ve installed the pthread.lib file and pthread.h file into the respective lib/header directories, where all of the other files are. The DLL on the other hand (the actual library), I’ve placed in c:\windows\system32. I’ve tried to add the DLL as a dependency (right click project -> references -> Add new reference), but as others have stated, all I get is a blank dialogue box with no option to add any DLL files or anything. It seems to recognize the header file, but I get these errors when I compile:

1>main.obj : error LNK2019: unresolved external symbol _imp_pthread_join referenced in function _main

1>main.obj : error LNK2019: unresolved external symbol _imp_pthread_create referenced in function _main

1>main.obj : error LNK2019: unresolved external symbol _imp_pthread_exit referenced in function _fcount

From my research, I’ve determined that this is a problem with the DLL, and I’m assuming it can’t find the definitions of the functions I’ve referenced in my code. I’ve searched high and low and I can’t seem to figure out any way to overcome this problem. I’ve added the directories of the lib/header files to my linker, just in-case, but that didn’t solve the issue. I need to do something, in visual studio, to specify that I need pthreadVC2.dll as a project dependency — and it seems to be impossible (and extremely frustrating) at this point.

CreateThread function (processthreadsapi.h)

Creates a thread to execute within the virtual address space of the calling process.

To create a thread that runs in the virtual address space of another process, use the CreateRemoteThread function.

Syntax

Parameters

A pointer to a SECURITY_ATTRIBUTES structure that determines whether the returned handle can be inherited by child processes. If lpThreadAttributes is NULL, the handle cannot be inherited.

The lpSecurityDescriptor member of the structure specifies a security descriptor for the new thread. If lpThreadAttributes is NULL, the thread gets a default security descriptor. The ACLs in the default security descriptor for a thread come from the primary token of the creator.

The initial size of the stack, in bytes. The system rounds this value to the nearest page. If this parameter is zero, the new thread uses the default size for the executable. For more information, see Thread Stack Size.

A pointer to the application-defined function to be executed by the thread. This pointer represents the starting address of the thread. For more information on the thread function, see ThreadProc.

Читайте также:  From windows phone to mac os

A pointer to a variable to be passed to the thread.

The flags that control the creation of the thread.

Value Meaning
0 The thread runs immediately after creation.
CREATE_SUSPENDED 0x00000004 The thread is created in a suspended state, and does not run until the ResumeThread function is called.
STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000 The dwStackSize parameter specifies the initial reserve size of the stack. If this flag is not specified, dwStackSize specifies the commit size.

A pointer to a variable that receives the thread identifier. If this parameter is NULL, the thread identifier is not returned.

Return value

If the function succeeds, the return value is a handle to the new thread.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Note that CreateThread may succeed even if lpStartAddress points to data, code, or is not accessible. If the start address is invalid when the thread runs, an exception occurs, and the thread terminates. Thread termination due to a invalid start address is handled as an error exit for the thread’s process. This behavior is similar to the asynchronous nature of CreateProcess, where the process is created even if it refers to invalid or missing dynamic-link libraries (DLLs).

Remarks

The number of threads a process can create is limited by the available virtual memory. By default, every thread has one megabyte of stack space. Therefore, you can create at most 2,048 threads. If you reduce the default stack size, you can create more threads. However, your application will have better performance if you create one thread per processor and build queues of requests for which the application maintains the context information. A thread would process all requests in a queue before processing requests in the next queue.

The new thread handle is created with the THREAD_ALL_ACCESS access right. If a security descriptor is not provided when the thread is created, a default security descriptor is constructed for the new thread using the primary token of the process that is creating the thread. When a caller attempts to access the thread with the OpenThread function, the effective token of the caller is evaluated against this security descriptor to grant or deny access.

The newly created thread has full access rights to itself when calling the GetCurrentThread function.

Windows ServerВ 2003:В В The thread’s access rights to itself are computed by evaluating the primary token of the process in which the thread was created against the default security descriptor constructed for the thread. If the thread is created in a remote process, the primary token of the remote process is used. As a result, the newly created thread may have reduced access rights to itself when calling GetCurrentThread. Some access rights including THREAD_SET_THREAD_TOKEN and THREAD_GET_CONTEXT may not be present, leading to unexpected failures. For this reason, creating a thread while impersonating another user is not recommended.

If the thread is created in a runnable state (that is, if the CREATE_SUSPENDED flag is not used), the thread can start running before CreateThread returns and, in particular, before the caller receives the handle and identifier of the created thread.

The thread execution begins at the function specified by the lpStartAddress parameter. If this function returns, the DWORD return value is used to terminate the thread in an implicit call to the ExitThread function. Use the GetExitCodeThread function to get the thread’s return value.

The thread is created with a thread priority of THREAD_PRIORITY_NORMAL. Use the GetThreadPriority and SetThreadPriority functions to get and set the priority value of a thread.

When a thread terminates, the thread object attains a signaled state, satisfying any threads that were waiting on the object.

The thread object remains in the system until the thread has terminated and all handles to it have been closed through a call to CloseHandle.

Читайте также:  Windows phone для android 4pda

The ExitProcess, ExitThread, CreateThread, CreateRemoteThread functions, and a process that is starting (as the result of a call by CreateProcess) are serialized between each other within a process. Only one of these events can happen in an address space at a time. This means that the following restrictions hold:

  • During process startup and DLL initialization routines, new threads can be created, but they do not begin execution until DLL initialization is done for the process.
  • Only one thread in a process can be in a DLL initialization or detach routine at a time.
  • ExitProcess does not complete until there are no threads in their DLL initialization or detach routines.

A thread in an executable that calls the C run-time library (CRT) should use the _beginthreadex and _endthreadex functions for thread management rather than CreateThread and ExitThread; this requires the use of the multithreaded version of the CRT. If a thread created using CreateThread calls the CRT, the CRT may terminate the process in low-memory conditions.

Windows Phone 8.1: This function is supported for Windows Phone Store apps on Windows Phone 8.1 and later.

WindowsВ 8.1 and Windows ServerВ 2012В R2: This function is supported for Windows Store apps on WindowsВ 8.1, Windows ServerВ 2012В R2, and later.

Thread library in windows

plibsys is a cross-platform system C library with some helpful routines. It has zero third-party dependencies and uses only native system calls.

plibsys gives you:

  • Platform independent data types
  • Threads
  • Mutexes
  • Condition variables
  • Read-write locks
  • System-wide semaphores
  • System-wide shared memory
  • Optimized spinlock
  • Atomic operations
  • Socket support (UDP, TCP, SCTP) with IPv4 and IPv6
  • Hash functions: MD5, SHA-1, SHA-2, SHA-3, GOST (R 34.11-94)
  • Binary trees: BST, red-black, AVL
  • INI file parser
  • High resolution time profiler
  • Files and directories
  • Shared library loading
  • Useful routines for linked lists, strings, hash tables
  • Macros for CPU architecture, OS and compiler detection
  • Macros for variable arguments

To achieve maximum native performance on each platform several implementation models are used:

  • Threading models: POSIX, Solaris, OS/2, BeOS, AtheOS, AmigaOS and Win32
  • IPC models: POSIX, System V, OS/2, AmigaOS and Win32
  • Time profiler models: POSIX, Solaris, Mach, OS/2, BeOS, AmigaOS, Win32 and generic
  • Directory iterating models: POSIX, OS/2 and Win32
  • Shared library loading models: POSIX, HP-UX, OS/2, BeOS, AmigaOS and Win32
  • Atomic operations models: sync, C11, DECC, Win32 and simulated
  • Sockets: BSD with Win32 support

plibsys is a cross-platform, highly portable library, it is fully covered with unit tests and was tested on the following desktop platforms:

  • GNU/Linux
  • macOS
  • Windows
  • Cygwin, MSYS
  • FreeBSD, NetBSD, OpenBSD
  • DragonFlyBSD
  • Solaris
  • AIX
  • HP-UX
  • Tru64
  • OpenVMS
  • OS/2
  • IRIX
  • QNX Neutrino
  • UnixWare 7
  • SCO OpenServer 5
  • Haiku
  • Syllable
  • BeOS
  • AmigaOS

plibsys also supports the following mobile platforms:

  • iOS, watchOS, tvOS
  • Android
  • BlackBerry 10

It should also work on other *nix systems with or without minimal efforts.

plibsys was tested with the following compilers:

  • MSVC (x86, x64) 2003 and above
  • MinGW (x86, x64)
  • Open Watcom (x86)
  • Borland (x86)
  • GCC (x86, x64, PPC32be, PPC64be/le, IA-64/32, IA-64, Alpha, HPPA2.0-32, MIPS32, AArch32, SPARCv9)
  • Clang (x86, x64, PPC32be, AArch32, AArch64)
  • Intel (x86, x64)
  • QCC (x86, AArch32)
  • Oracle Solaris Studio (x86, x64, SPARCv9)
  • MIPSpro (MIPS32)
  • XL C (PPC64le)
  • DEC C (Alpha)
  • PGI (x86, x64)
  • Cray (x64)

Use CMake to build plibsys for target platform. For OpenVMS see platforms/vms-general directory.

Documentation for the latest stable verison is avaialble through the GitHub Pages.

plibsys is distributed under the terms of MIT license.

More information about the library is available on the Wiki.

About

Highly portable C system library: threads and synchronization primitives, sockets (TCP, UDP, SCTP), IPv4 and IPv6, IPC, hash functions (MD5, SHA-1, SHA-2, SHA-3, GOST), binary trees (RB, AVL) and more. Native code performance.

Оцените статью