Overview of Blocking vs Non-Blocking
In Bnlang, operations can be blocking or non-blocking.
- Blocking means the program waits until the operation finishes before moving on.
- Non-blocking means the program continues running other tasks while the operation works in the background.
Understanding this difference is key to writing efficient and responsive programs.
Blocking Example
// ব্লকিং ফাংশনের উদাহরণ
function ঘুমাও(ms) {
const শেষ = Date.now() + ms;
যতক্ষণ (Date.now() < শেষ) {}
}
কনসোল.লগ("শুরু");
ঘুমাও(2000); // ২ সেকেন্ড ব্লক করে
কনসোল.লগ("শেষ");
Non-Blocking Example
কনসোল.লগ("শুরু");
সময়সীমা_নির্ধারণ(() => {
কনসোল.লগ("টাইমআউটের ভেতরে");
}, 2000);
কনসোল.লগ("শেষ"); // সাথে সাথে প্রিন্ট হয়
Why Non-Blocking is Better
- Keeps programs responsive.
- Multiple tasks can progress together.
- Better for I/O operations like file read, network requests, and database queries.
Best Practices
- Avoid blocking operations in the main thread.
- Use asynchronous APIs for I/O tasks.
- Break heavy computations into smaller chunks or move them to workers.