Files
Claude 93a6e00f70 Suspend, resume and terminate running threads
SuspendThread now stops a running thread where it is: with Mach's
thread_suspend on macOS, and elsewhere with a signal whose handler waits
until the count is back to zero. ResumeThread counts down and lets it
go; a thread can suspend itself and be resumed by another. The count is
kept as on Windows (MAXIMUM_SUSPEND_COUNT, ERROR_SIGNAL_REFUSED).

TerminateThread stops a thread for good: before it starts, while it
runs, or while it is held. As on Windows, nothing it holds is let go
and its stack is not unwound; its handle is signaled with the exit code.

The cooperative threads of DOS and the classic Mac OS can still be held
only before they start.

core tests threads made suspended, held while running (and by
themselves), and terminated at each stage.

Signed-off-by: Claude <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B82eRRw4kkFHrrHRhkcuLw
2026-11-27 17:27:39 +00:00

371 lines
11 KiB
C++

// core.cpp - console tests for the non-window classes.
#include <afx.h>
#include <afxcoll.h>
#include <afxtempl.h>
#include <afxconv.h>
#ifndef _AFX_WIN16 // 16-bit Windows has the core classes only
#include <afxadv.h>
#endif
#include <stdio.h>
static int g_failures = 0;
#define CHECK(cond) \
do { \
if (!(cond)) { \
printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \
g_failures++; \
} \
} while (0)
class CShape : public CObject {
DECLARE_SERIAL(CShape)
public:
int m_nSides;
CString m_strName;
CShape() : m_nSides(0) {}
CShape(int n, LPCTSTR name) : m_nSides(n), m_strName(name) {}
virtual void Serialize(CArchive& ar) {
CObject::Serialize(ar);
if (ar.IsStoring())
ar << m_nSides << m_strName;
else
ar >> m_nSides >> m_strName;
}
};
IMPLEMENT_SERIAL(CShape, CObject, 1)
class CSquare : public CShape {
DECLARE_SERIAL(CSquare)
public:
CSquare() : CShape(4, _T("square")) {}
};
IMPLEMENT_SERIAL(CSquare, CShape, 1)
static void TestString() {
CString s = _T("Hello");
s += _T(", world");
CHECK(s == _T("Hello, world"));
CHECK(s.GetLength() == 12);
CHECK(s.Find(_T("world")) == 7);
CHECK(s.Left(5) == _T("Hello"));
CHECK(s.Mid(7) == _T("world"));
CHECK(s.Right(5) == _T("world"));
CString t;
t.Format(_T("%d-%s-%04x"), 42, _T("x"), 0xab);
CHECK(t == _T("42-x-00ab"));
CString u = _T(" trim me ");
u.Trim();
CHECK(u == _T("trim me"));
CString v = _T("a,b,,c");
int iStart = 0;
CString tok1 = v.Tokenize(_T(","), iStart);
CString tok2 = v.Tokenize(_T(","), iStart);
CString tok3 = v.Tokenize(_T(","), iStart);
CHECK(tok1 == _T("a") && tok2 == _T("b") && tok3 == _T("c"));
v.Replace(_T(','), _T(';'));
CHECK(v == _T("a;b;;c"));
CString w = v; // shares the buffer until written
w.MakeUpper();
CHECK(v == _T("a;b;;c") && w == _T("A;B;;C"));
CStringA a("narrow");
CStringW wide(a);
CHECK(wide == L"narrow");
CString sub;
CHECK(AfxExtractSubString(sub, _T("one\ntwo\nthree"), 1) && sub == _T("two"));
}
static void TestCollections() {
CStringArray arr;
arr.Add(_T("b"));
arr.Add(_T("a"));
arr.InsertAt(0, _T("c"));
CHECK(arr.GetSize() == 3 && arr[0] == _T("c") && arr[2] == _T("a"));
arr.RemoveAt(1);
CHECK(arr.GetSize() == 2 && arr[1] == _T("a"));
CMapStringToPtr map;
int one = 1, two = 2;
map[_T("one")] = &one;
map.SetAt(_T("two"), &two);
void* p = NULL;
CHECK(map.Lookup(_T("two"), p) && p == &two);
CHECK(!map.Lookup(_T("three"), p));
CHECK(map.GetCount() == 2);
CList<int, int> list;
for (int i = 0; i < 5; i++) list.AddTail(i);
CHECK(list.GetCount() == 5 && list.GetHead() == 0 && list.GetTail() == 4);
POSITION pos = list.Find(3);
CHECK(pos != NULL);
list.RemoveAt(pos);
CHECK(list.GetCount() == 4 && list.Find(3) == NULL);
CMap<int, int, CString, LPCTSTR> imap;
imap[7] = _T("seven");
CString val;
CHECK(imap.Lookup(7, val) && val == _T("seven"));
CArray<SIZE, const SIZE&> pts;
pts.SetSize(3);
SIZE sz = {5, 6};
pts[2] = sz;
CHECK(pts.GetCount() == 3 && pts[2].cx == 5);
CObList objs;
objs.AddTail(new CSquare);
objs.AddTail(new CShape(3, _T("triangle")));
CHECK(objs.GetCount() == 2);
while (!objs.IsEmpty()) delete objs.RemoveHead();
}
static void TestRuntimeClass() {
CObject* p = RUNTIME_CLASS(CSquare)->CreateObject();
CHECK(p != NULL);
CHECK(p->IsKindOf(RUNTIME_CLASS(CShape)));
CHECK(p->IsKindOf(RUNTIME_CLASS(CObject)));
CHECK(!RUNTIME_CLASS(CShape)->IsDerivedFrom(RUNTIME_CLASS(CSquare)));
CHECK(strcmp(p->GetRuntimeClass()->m_lpszClassName, "CSquare") == 0);
CHECK(CRuntimeClass::FromName("CShape") == RUNTIME_CLASS(CShape));
delete p;
}
static void TestArchive() {
CMemFile file;
{
CArchive ar(&file, CArchive::store);
CShape tri(3, _T("triangle"));
CSquare sq;
CObject* pShape = &sq;
ar << (DWORD)0x12345678 << (short)-2 << 3.5 << CString(_T("text"));
tri.Serialize(ar);
ar << pShape;
ar << pShape; // the second time only a reference is written
ar.Close();
}
file.SeekToBegin();
{
CArchive ar(&file, CArchive::load);
DWORD dw;
short sh;
double d;
CString str;
ar >> dw >> sh >> d >> str;
CHECK(dw == 0x12345678 && sh == -2 && d == 3.5 && str == _T("text"));
CShape tri;
tri.Serialize(ar);
CHECK(tri.m_nSides == 3 && tri.m_strName == _T("triangle"));
CObject* p1 = NULL;
CObject* p2 = NULL;
ar >> p1 >> p2;
CHECK(p1 != NULL && p1 == p2 && p1->IsKindOf(RUNTIME_CLASS(CSquare)));
CHECK(((CShape*)p1)->m_nSides == 4);
delete p1;
}
}
static void TestFileAndExceptions() {
TCHAR szTemp[MAX_PATH], szPath[MAX_PATH];
::GetTempPath(MAX_PATH, szTemp);
::GetTempFileName(szTemp, _T("mfc"), 0, szPath);
{
CFile f(szPath, CFile::modeCreate | CFile::modeWrite);
f.Write("abc", 3);
}
{
CFile f(szPath, CFile::modeRead);
char buf[8] = {0};
CHECK(f.Read(buf, 8) == 3 && strcmp(buf, "abc") == 0);
CHECK(f.GetLength() == 3);
}
{
CFileStatus status;
CHECK(CFile::GetStatus(szPath, status) && status.m_size == 3);
CFileFind find;
CHECK(find.FindFile(szPath));
find.FindNextFile();
CHECK(find.GetLength() == 3 && !find.IsDirectory());
CString strPath(szPath);
int iName = max(strPath.ReverseFind(_T('\\')), strPath.ReverseFind(_T('/'))) + 1;
CHECK(find.GetFileName().CompareNoCase(strPath.Mid(iName)) == 0);
}
CFile::Remove(szPath);
CFileStatus gone;
CHECK(!CFile::GetStatus(szPath, gone));
BOOL bCaught = FALSE;
try {
CFile f(_T("Z:\\no\\such\\dir\\file.txt"), CFile::modeRead);
} catch (CFileException* e) {
bCaught = e->m_cause == CFileException::fileNotFound || e->m_cause == CFileException::badPath;
e->Delete();
}
CHECK(bCaught);
bCaught = FALSE;
TRY { AfxThrowUserException(); }
CATCH(CUserException, e) { bCaught = TRUE; }
END_CATCH
CHECK(bCaught);
}
static void TestTime() {
CTime t(2024, 2, 29, 13, 45, 30);
CHECK(t.GetYear() == 2024 && t.GetMonth() == 2 && t.GetDay() == 29);
CHECK(t.Format(_T("%Y-%m-%d %H:%M:%S")) == _T("2024-02-29 13:45:30"));
CTimeSpan span(1, 2, 3, 4);
CTime t2 = t + span;
CHECK(t2.GetDay() == 1 && t2.GetMonth() == 3 && t2.GetHour() == 15);
CHECK((t2 - t).GetTotalSeconds() == span.GetTotalSeconds());
}
static void TestConversion() {
USES_CONVERSION;
#ifdef _WINPORT
LPCWSTR pszW = A2W("caf\xc3\xa9"); // e-acute in UTF-8, the ANSI code page there
#else
LPCWSTR pszW = A2W("caf\xe9"); // e-acute in Windows-1252
#endif
CHECK(lstrlenW(pszW) == 4 && pszW[3] == 0xE9);
CHECK(lstrcmpA(W2A(L"plain"), "plain") == 0);
CHECK(lstrcmp(A2T("abc"), _T("abc")) == 0);
CHECK(lstrcmpA(T2A(_T("xyz")), "xyz") == 0);
CHECK(lstrcmp(OLE2T(L"ole"), _T("ole")) == 0);
CHECK(A2W((LPCSTR)NULL) == NULL);
// The classes, including code pages and strings longer than the buffer.
// (16-bit Windows has the ANSI code page only.)
#ifndef _AFX_WIN16
CHECK(lstrcmpA(CW2A(L"\x20AC", CP_UTF8), "\xE2\x82\xAC") == 0);
CHECK(lstrcmpW(CA2W("\xE2\x82\xAC", CP_UTF8), L"\x20AC") == 0);
#endif
CStringA strLong('x', 500);
CHECK(lstrlenW(CA2W(strLong)) == 500);
CHECK(lstrcmp(CA2T("t"), _T("t")) == 0);
CHECK(lstrcmpA(CT2A(_T("u")), "u") == 0);
CHECK(lstrcmpW(CT2W(_T("w")), L"w") == 0);
#ifndef _AFX_WIN16
BSTR bstr = A2BSTR("bstr");
CHECK(bstr != NULL && ::SysStringLen(bstr) == 4);
::SysFreeString(bstr);
#endif
}
#ifndef _AFX_WIN16
static void TestSharedFile() {
CSharedFile file;
CArchive ar(&file, CArchive::store);
ar << (DWORD)0x12345678 << CString(_T("shared"));
ar.Close();
ULONGLONG nLength = file.GetLength();
HGLOBAL hMem = file.Detach();
CHECK(hMem != NULL && ::GlobalSize(hMem) >= nLength);
CHECK(file.GetLength() == 0);
// Read it back from the handle, as a clipboard reader would.
CSharedFile file2;
file2.SetHandle(hMem, FALSE);
CArchive ar2(&file2, CArchive::load);
DWORD dw = 0;
CString str;
ar2 >> dw >> str;
ar2.Close();
CHECK(dw == 0x12345678 && str == _T("shared"));
file2.Close();
::GlobalFree(hMem); // SetHandle leaves the memory the caller's
}
#endif
#ifndef _AFX_WIN16
// Threads held and let go, stopped while they run, and ended from
// outside. The cooperative threads of DOS and the classic Mac OS can be
// held only before they start.
static volatile LONG g_spins = 0;
static DWORD WINAPI Spin(LPVOID) {
for (;;) ::InterlockedIncrement(&g_spins);
}
static DWORD WINAPI Quick(LPVOID p) { return (DWORD)(DWORD_PTR)p; }
static DWORD WINAPI SuspendSelf(LPVOID p) {
::SuspendThread(::GetCurrentThread());
*(volatile LONG*)p = 1;
return 7;
}
static void TestThreads() {
// Made suspended: nothing runs until the count is back to zero.
HANDLE h = ::CreateThread(NULL, 0, Quick, (LPVOID)42, CREATE_SUSPENDED, NULL);
CHECK(h != NULL);
CHECK(::SuspendThread(h) == 1);
CHECK(::ResumeThread(h) == 2);
CHECK(::WaitForSingleObject(h, 100) == WAIT_TIMEOUT);
CHECK(::ResumeThread(h) == 1);
CHECK(::WaitForSingleObject(h, 5000) == WAIT_OBJECT_0);
DWORD code = 0;
CHECK(::GetExitCodeThread(h, &code) && code == 42);
CHECK(::ResumeThread(h) == 0 || ::ResumeThread(h) == (DWORD)-1);
::CloseHandle(h);
// Ended before it began.
h = ::CreateThread(NULL, 0, Quick, (LPVOID)1, CREATE_SUSPENDED, NULL);
CHECK(::TerminateThread(h, 99));
CHECK(::WaitForSingleObject(h, 5000) == WAIT_OBJECT_0);
CHECK(::GetExitCodeThread(h, &code) && code == 99);
::CloseHandle(h);
#if !defined(__MSDOS__) && !defined(macintosh)
// Stopped while it runs: the counter stands still, then goes on.
h = ::CreateThread(NULL, 0, Spin, NULL, 0, NULL);
while (g_spins < 1000) ::Sleep(1);
CHECK(::SuspendThread(h) == 0);
CHECK(::SuspendThread(h) == 1);
LONG at = g_spins;
::Sleep(50);
CHECK(g_spins == at);
CHECK(::ResumeThread(h) == 2);
::Sleep(20);
CHECK(g_spins == at);
CHECK(::ResumeThread(h) == 1);
::Sleep(50);
CHECK(g_spins != at);
CHECK(::GetExitCodeThread(h, &code) && code == STILL_ACTIVE);
// Ended while it runs, and while it is held.
CHECK(::TerminateThread(h, 5));
CHECK(::WaitForSingleObject(h, 5000) == WAIT_OBJECT_0);
at = g_spins;
::Sleep(30);
CHECK(g_spins == at);
CHECK(::GetExitCodeThread(h, &code) && code == 5);
::CloseHandle(h);
h = ::CreateThread(NULL, 0, Spin, NULL, 0, NULL);
::Sleep(10);
CHECK(::SuspendThread(h) == 0);
CHECK(::TerminateThread(h, 6));
CHECK(::WaitForSingleObject(h, 5000) == WAIT_OBJECT_0);
CHECK(::GetExitCodeThread(h, &code) && code == 6);
::CloseHandle(h);
// A thread that holds itself, let go by another.
volatile LONG went = 0;
h = ::CreateThread(NULL, 0, SuspendSelf, (LPVOID)&went, 0, NULL);
::Sleep(50);
CHECK(went == 0);
CHECK(::ResumeThread(h) == 1);
CHECK(::WaitForSingleObject(h, 5000) == WAIT_OBJECT_0);
CHECK(went == 1 && ::GetExitCodeThread(h, &code) && code == 7);
::CloseHandle(h);
#endif
}
#endif
int main() {
TestConversion();
#ifndef _AFX_WIN16
TestSharedFile();
TestThreads();
#endif
TestString();
TestCollections();
TestRuntimeClass();
TestArchive();
TestFileAndExceptions();
TestTime();
printf("%s: %d failure(s)\n", g_failures ? "FAIL" : "PASS", g_failures);
return g_failures ? 1 : 0;
}